Search code examples
awkfilenamesbasename

Add file name as a new column with awk


First of all existing questions didn't solve my problem that's why I am asking again.

I have two txt files temp.txt

adam    12
george  15
thomas  20

and demo.txt

mark    8
richard 11
james   18

I want to combine them and add a 3rd column as their file names without extension, like this:

adam    12   temp
george  15   temp
thomas  20   temp
mark    8    demo
richard 11   demo
james   18   demo

I used this script:

for i in $(ls); do name=$(basename -s .txt $i)| awk '{OFS="\t";print $0, $name} ' $i; done

But it yields following table:

mark    8   mark    8
richard 11  richard 11
james   18  james   18
adam    12  adam    12
george  15  george  15
thomas  20  thomas  20

I don't understand why it gives the name variable as the whole table.

Thanks in advance.


Solution

  • First, you need to unmask $name which is inside the single quotes, so does not get replaced by the filename from the shell. After you do that, you need to add double quotes around $name so that awk sees that as a string:

    for i in $(ls); do name=$(basename -s .txt $i); awk '{OFS="\t";print $0, "'$name'"} ' $i; done