Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print name of the file in front of every line of file

I have a lot of text files and I want to make a bash script in linux to print the name of file in each lines of file. For example I have file lenovo.txt and I want that every line in the file to start with lenovo.txt.

I try to make a "for" for this but didn't work.

for i in *.txt
do
        awk '{print '$i' $0}' /var/SambaShare/$i > /var/SambaShare/new_$i
done

Thanks!

like image 504
antiks Avatar asked Jan 10 '23 01:01

antiks


2 Answers

It doesn't work because you need to pass $i to awk with the -v option. But you can also use the FILENAME built-in variable in awk :

ls *txt
file.txt    file2.txt

cat *txt
A
B
C
A2
B2
C2

for i in *txt; do 
awk '{print FILENAME,$0}' $i; 
done
file.txt A
file.txt B
file.txt C
file2.txt A2
file2.txt B2
file2.txt C2

An to redirect into a new file :

for i in *txt; do 
awk '{print FILENAME,$0}' $i > ${i%.txt}_new.txt; 
done

As for your corrected version :

for i in *.txt
do
        awk -v i=$i '{print i,$0}' $i > new_$i
done

Hope this helps.

like image 148
jrjc Avatar answered Jan 12 '23 13:01

jrjc


Using grep you can make use of the --with-filename (alias -H) option and use an empty pattern that always matches:

for i in *.txt
do
    grep -H "" $i > new_$i
done
like image 20
Jens Wirth Avatar answered Jan 12 '23 15:01

Jens Wirth