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?
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
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
to do in-place editing of the files.
Perl also allows this. It all depends
on what other tools you have available. :)