Home > Blockchain >  Insert filename as column, separated by a comma
Insert filename as column, separated by a comma

Time:10-28

I have 100 file that looks like this

>file.csv
gene1,55
gene2,23
gene3,33

I want to insert the filename and make it look like this:

file.csv
gene1,55,file.csv
gene2,23,file.csv
gene3,33,file.csv

Now, I can almost get there using awk

awk '{print $0,FILENAME}' *.csv > concatenated_files.csv

But this prints the filenames with a space, instead of a comma. Is there a way to replace the space with a comma?

CodePudding user response:

Is there a way to replace the space with a comma?

Yes, change the OFS

$ awk -v OFS="," '{print $0,FILENAME}' file.csv
gene1,55,file.csv
gene2,23,file.csv
gene3,33,file.csv

CodePudding user response:

Figured it out, turns out:

for d in *.csv; do (awk '{print FILENAME (NF?",":"") $0}' "$d" > ${d}.all_files.csv); done

Works just fine.

CodePudding user response:

You can also create a new field

awk -vOFS=, '{$  NF=FILENAME}1' file.csv
gene1,55,file.csv
gene2,23,file.csv
gene3,33,file.csv
  • Related