write filename as first line in a txt file

Could anyone very kindly help me a simple way to perform the - perhaps - very trivial task of writing the name of a file as first line of that file which is in txt format?

And would be possible to do this recursively for some thousands files in the XY directory?

And, again, add to the simple filename also the folder name (say <XY/nomefile.txt>)

Thanks a lot for any help!

mjomba from Tanzania

This code could help get started as you require..

# place the script in the dir where filenames need to be added to the .txt file
# use mv to change to original filename if needed: mv $filename.new $filename

for filename in $(ls *.txt)
do
	sed "1s/^/${filename} \n/" ${filename} > $filename.new 
	echo Done ${filename} 
done

Refer this post as well.

As you also need the directory name...:slight_smile: Modified michaelrozar17's reply...:b:

 
# place the script in the dir where filenames need to be added to the .txt file
# You can remove the comments if that's what you want...
for filename in $(ls -1 *.txt)
do
        pwd=${PWD}/${filename}
        awk 'BEGIN{print "'$pwd'"}1' $filename > $filename.new
        #rm -f $filename
        #mv $filename.new $filename
done
perl -i -pe 'BEGIN{undef $/;} s/^/$ARGV\n/' `find . -name '*.txt'`