tags:

views:

113

answers:

4

I am using cat *.txt to merge multiple txt files into one, but I need each file to be on a separate line.

What is the best way to merge files with each file appearing on a new line?

+1  A: 
for file in *.txt
do
  cat "$file"
  echo
done > newfile
Ignacio Vazquez-Abrams
+4  A: 

You can iterate through each file with a for loop:

for filename in *.txt; do
    # each time through the loop, ${filename} will hold the name
    # of the next *.txt file.  You can then arbitrarily process
    # each file
    cat "${filename}"
    echo

# You can add redirection after the done (which ends the
# for loop).  Any output within the for loop will be sent to
# the redirection specified here
done > output_file
R Samuel Klatchko
This will choke on files that have a space in the filename.
Ignacio Vazquez-Abrams
@IgnacioVazquezAbrams - thanks for the reminder (I don't use spaces in my names so I usually forget that). Anyway, I've updated my example to handle that properly.
R Samuel Klatchko
I picked the awk solution, but this will definitely come in useful for other scripts. Thanks.
Marco
A: 

I'm assuming you want a line break between files.

for file in *.txt
do
   cat "$file" >> result
   echo >> result
done
Matthew Flaschen
+2  A: 

just use awk

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