I have a bunch of text (hundreds of txt) inside a directory. Each of them has a unique filename. I want to insert filename of each file into the first line of respective files. How can I do that using bash script?
3 Answers
Standard approach is to use temporary files, but you can change files in place if you enclose cat in $() parenthesis:
for file in *.txt; do echo "$file"$'\n'"$(cat -- "$file")" > "$file"; done
-
if file name has a space in it then??αғsнιη– αғsнιη2014-09-26 07:27:29 +00:00Commented Sep 26, 2014 at 7:27
-
@KasiyA Just put double quotes everywhere required.Gilles 'SO- stop being evil'– Gilles 'SO- stop being evil'2014-09-26 22:33:34 +00:00Commented Sep 26, 2014 at 22:33
You could use the standard text editor:
for f in *; do printf '%s\n' 1i "$f" . w q | ed "$f"; done
for file in *; do
(echo "$file"; cat -- "$file") > "$file.new"
mv -- "$file.new" "$file"
done
This loops over all files
echoes each filename and
appends the contents of the file
then all placing it into a new file
with the additional suffix of .new.
You create a new file for each existing one, so you must rename the files afterwards.
You can place the results into a new directory and then remove the old one:
mkdir new
for file in *; do
(echo "$file"; cat "$file") > "new/$file"
done
You can also use sed with option -i
to do in-place editing of the files.
Perl also allows this. It all depends
on what other tools you have available. :)