2

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

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нιη Sep 26 '14 at 7:27
  • @KasiyA Just put double quotes everywhere required. – Gilles Sep 26 '14 at 22:33
1

You could use the standard text editor:

for f in *; do printf '%s\n' 1i "$f" . w q | ed "$f"; done
1
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. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.