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?


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

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"

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"

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.