Add filenames to top of each files in a directory

Hello,

I tried different solutions given in various linux portals but no luck..

The directory consists of files with no-extension.
Each file has only one line. I need to add each filename to the top of each file so eventually each file will have two rows.
Filenames have spaces between words and some files have multiple spaces at the end of their names.

At first I tried this one:

while read F ; do
grep sed  -i '1i $F' $F > $F.txt
done

Also below one is not working:

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

sleep 2

Any help will be appreciated

Kind regards
Boris

Hello baris35,

Could you please try following(I haven't tested it though).

for file in *
do
    awk 'NR==1{print FILENAME} 1' $file > $file".tmp"
    mv $file".tmp" $file
done
 

Thanks,
R. Singh

1 Like

for FILE in `ls *` is a dangerous use of backticks and pointless besides, don't do that. * does not need ls or any other external command's help to work.

You can do this with a subshell, which first prints the file name, then reads out the file contents, with the entire subshell's output dumped into "$FILE".txt

for FILE in *
do
        ( echo "$FILE" ; cat "$FILE" ) < "$FILE" > "$FILE".txt
done
1 Like

Hello Ravinder,
Thanks for your answer,
it gives error for some reason:

line 5: $file".tmp": ambiguous redirect

Hello Corona,
Thanks for the answer, that is working as expected.

Many Thanks!
Boris

Hello baris35,

Not sure about it, could you please check following and let me know if this helps you.(I tested now previous code and it worked fine for me)

for file in *
do
    awk 'NR==1{print FILENAME} 1' $file > "$file.tmp"
    mv "$file.tmp" $file
done

Thanks,
R. Singh

Hello Ravinder,

Here is the output:

awk: cannot open #EXTINF:0,DE: (No such file or directory)
mv: target �CY� is not a directory
awk: cannot open #EXTINF:0,DE: (No such file or directory)
mv: target �.txt� is not a directory
awk: cannot open #EXTINF:0,DE: (No such file or directory)
mv: target �.txt� is not a directory

Kind regards
Boris

You cannot possibly have been running the code he gave you.

Show exactly what you did please, word for word, letter for letter, keystroke for keystroke.