Shell – Concatenate filename inside of CSV file for each line for multiple CSV files

csvshell-script

I have lots of CSV files and I need the filename of each specific CSV file in every line of each file.

Original file content of abc123.csv:

ColVal_1;ColVal_2;ColVal_3
ColVal_4;ColVal_5;ColVal_6

New file content:

ColVal_1;ColVal_3;ColVal_3;abc123.csv
ColVal_4;ColVal_5;ColVal_6;abc123.csv

All CSV files are in the same directory. I don't want to specify the name of each file.

Best Answer

Its much more simple, easier and faster with sed and xargs. Here sed uses in-place editing thus avoiding additional shell tools.

$ ls file{1..5}.txt|xargs -I% sed -i 's/$/;%/' %

And here is the output.

$ cat file{1..5}.txt
ColVal_1;ColVal_2;ColVal_3;file1.txt
ColVal_4;ColVal_5;ColVal_6;file1.txt
ColVal_1;ColVal_2;ColVal_3;file2.txt
ColVal_4;ColVal_5;ColVal_6;file2.txt
ColVal_1;ColVal_2;ColVal_3;file3.txt
ColVal_4;ColVal_5;ColVal_6;file3.txt
ColVal_1;ColVal_2;ColVal_3;file4.txt
ColVal_4;ColVal_5;ColVal_6;file4.txt
ColVal_1;ColVal_2;ColVal_3;file5.txt
ColVal_4;ColVal_5;ColVal_6;file5.txt
Related Question