I would like to concatenate multiple .txt files in one single file, putting also the file name as the first column before each file (in order to understand from which file the data comes from). The code I am using below does this, but only for the first row.
for i in *.txt; do echo -n "$i," && cat "$i"; done > tmpfile; mv tmpfile all-files.txt;
for example output like this:
filename1.txt,COVERAGE SUMMARY,,Aligned bases in genome,80754336928,100.00
filename1.txt,COVERAGE SUMMARY,,Average alignment coverage over genome,26.55
filename2.txt,COVERAGE SUMMARY,,Aligned bases in genome,88896465740,100.00
filename2.txt,COVERAGE SUMMARY,,Average alignment coverage over genome,33.40
CodePudding user response:
suggesting gawk
command:
To print the filename followed by ,
in first line of each file.
gawk 'BEGINFILE{printf("%s,",FILENAME)}1' *.txt
To print the filename followed by ,
in every line of each file.
awk '{print FILENAME "," $0}' *.txt
CodePudding user response:
I'd propose the use of awk:
for f in *.txt; do awk "{print \"$f, \" \$0}" "$f"; done