Print the filename before each line of the file

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

I'm trying to do this "for" but didn't work.

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

      

Thank!

+3


source to share


3 answers


It doesn't work because you need to pass $i

to awk with an option -v

. But you can also use the built-in variable FILENAME

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 to a new file:

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

      



As for the revised version:

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

      

Hope it helps.

+4


source


Awk and Bash do not have the same variables as they are different languages ​​with separate interpreters. You must pass Bash variables to Awk with an option -v

.

You must also specify filename variables to make sure they don't expand as separate arguments if they contain spaces.



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

      

+2


source


Using grep you can use the --with-filename

(alias -H

) option and use an empty pattern which always matches:

for i in *.txt
do
    grep -H "" $i > new_$i
done

      

+2


source







All Articles