Concatenating Files And Insert New Line In Between Files

neversaint picture neversaint · Nov 18, 2011 · Viewed 119.6k times · Source

I have multiple files which I want to concat with cat. Let's say

File1.txt 
foo

File2.txt
bar

File3.txt
qux

I want to concat so that the final file looks like:

foo

bar

qux

Instead of this with usual cat File*.txt > finalfile.txt

foo
bar 
qux

What's the right way to do it?

Answer

codaddict picture codaddict · Nov 18, 2011

You can do:

for f in *.txt; do (cat "${f}"; echo) >> finalfile.txt; done

Make sure the file finalfile.txt does not exist before you run the above command.

If you are allowed to use awk you can do:

awk 'FNR==1{print ""}1' *.txt > finalfile.txt