I want to cat all the files in a directory, but include some spacer between each one.
5 Answers
use awk
awk 'FNR==1{print ""}{print}' file* > out.txt
-
Nasty recursion. But this works: awk 'FNR==1{print ""}{print}' *.txt > /tmp/out.txt– MattOct 31, 2009 at 1:46
-
-
1If I run that line alone the command never quits, and keeps appending the files to the out.txt (which is in the same folder of the files I'm cat-ing. Out.txt gets very large, very fast. (Again, OSX 10.5.8 YRMV).– MattOct 31, 2009 at 1:58
-
file* in my example means processing files with file names starting with file. therefore if you have names like file1, file2, file3 then it will process. The only difference now is you change to *.txt. I could only guess that you have MANY files with names starting with file?? If not, I don't see why it will into recursion and never quits, as it works for me. Anyway, since there's a work around for you, then should be fine. Oct 31, 2009 at 2:04
-
2
awk 'FNR==1{}{print}' file* > out.txt
worked better for me. Thanks.– rahul286Jun 12, 2014 at 11:38
Try
find . -type f -exec cat {} \; -exec echo "-- spacer --" \;
Obviously, the 'spacer' can be more than the simple example used here.
-
-
Just use
echo ""
for a blank line. I should have said the spacer could be more or less than the example.– paviumOct 31, 2009 at 2:29 -
sounds like you have a different implementation than mine. How about
echo ''
or justecho
?– paviumOct 31, 2009 at 2:33 -
The
-printf "\n"
"action" is also viable; I believe it also avoids invoking echo or any other subprocess. Dec 4, 2016 at 8:44
You might want to see pr(1)
, which may do what you want out-of-the-box.
To roll your own, expand this posix shell script fragment:
ls -1 | while read f; do cat "$f"; echo This is a spacer line; done > /tmp/outputfile
This might more readably be written as:
ls -1 | while read f; do
cat "$f"
echo This is a spacer line
done > /tmp/outputfile
You don't really need the -1
for ls
.
-
Thanks! Just remember to redirect the output to another directory (as in the awk solution).– MattOct 31, 2009 at 1:55
-
You don't need the
ls
at all. Justfor f in *; do cat ...
(porkmail.org/era/unix/award.html#ls)– JacktoseMar 19, 2019 at 20:18
I think the simplest way is using the paste
command:
paste $(ls *) > file.out
-
Um, no, this just doesn't work. Paste does something similar but different to what the question asked. It interlaces the files.– CalebDec 10, 2016 at 14:07
echo "" > blank.txt
cat f1.txt blank.txt f2.txt blank.txt f3.txt
To handle all of the files in a Directory (assuming ksh like Shell)
for file in * ; do
cat $file >> result.txt
echo "" >> result.txt
done
-
That doesn't take care of all files in the directory unless you manually list them as parameters. Oct 31, 2009 at 1:29
-
be careful if you cat like that with a for loop expanding everything. $file could be a directory and you will be catting a directory. Oct 31, 2009 at 1:59