Append Multiple files with file name in the beginning of line

Hi,

I have multiple files having many lines like as bvelow:

file Name a.txt
abc    def
def    xyz
123   5678
file Name b.txt
abc def
def xyz
123 5678

I would like to append files in the below format to a new file:

file Name c.txt
a.txt:abc    def
a.txt:def    xyz
a.txt:123   5678
b.txt:abc def
b.txt:def xyz
b.txt:123 5678

like above input files I have apprx 500 files and each file does contain thousends of records, which need to be murged into single file

Please help

awk 'BEGIN{print "file name","out.txt"}FNR>1{print FILENAME":"$0}' *.txt
1 Like
grep . {a,b}.txt >c.txt

Or a little more elaborated:

f="c.txt"; ( echo "file Name $f"; grep -v file {a,b}.txt ) >$f

Small change as you miss first line with FNR>1

$ awk 'BEGIN{print "file name","out.txt"}{$0=FILENAME":"$0}1' *.txt

file name out.txt
a.txt:abc    def
a.txt:def    xyz
a.txt:123   5678
b.txt:abc def
b.txt:def xyz
b.txt:123 5678

The way you provide your requirement was a bit confusing :
I guess he was assuming that the first line was like

"file Name a.txt"

or

"file Name b.txt"

That's why he added the FNR>1 to skip those lines.

If the first line of your files are not supposed to contain the filename and must just contain datas, then the suggested

grep . {a,b}.txt >c.txt

should be sufficient to do what you need :

# cat a.txt
abc    def
def    xyz
123   5678
# cat b.txt
abc def
def xyz
123 5678
# cat c.txt
cat: c.txt: Aucun fichier ou répertoire de ce type
# grep . {a,b}.txt >c.txt
# cat c.txt
a.txt:abc    def
a.txt:def    xyz
a.txt:123   5678
b.txt:abc def
b.txt:def xyz
b.txt:123 5678
#

Hi,

Thanks for all you support, and regret for the confusion created, actually below code worked the desired output, I was required simplly the file name to be added at the beginning of each line item

awk 'BEGIN{$0=FILENAME":"$0}1' *.txt

Note that if an input file contains any empty lines (i.e., just a <newline> character), they will not appear in the output produced by the above command.

However, the command:

grep '^' *.txt > output

should do what was requested. (Note that if the input files are matched by the pattern *.txt , the output file must not also match that pattern unless it is located in a different directory so the input file pattern won't match the output file's pathname.

1 Like

I didn't think about using ^ ... good idea ! :smiley: