I want to cat all the files in a directory, but include some spacer between each one.
A:
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
Rob Moore
2009-10-31 01:20:31
That doesn't take care of all files in the directory unless you manually list them as parameters.
Ian Gregory
2009-10-31 01:29: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.
ghostdog74
2009-10-31 01:59:39
Nasty recursion. But this works: awk 'FNR==1{print ""}{print}' *.txt > /tmp/out.txt
Matt
2009-10-31 01:46:32
If 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).
Matt
2009-10-31 01:58:57
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.
ghostdog74
2009-10-31 02:04:33
EDIT-I'm a noob, and was doing `* > out.txt`, duh. Your answer is great (but not "cat", not sure I should select it as the "real" answer?). Thanks much.
Matt
2009-10-31 02:28:25
A:
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
.
DigitalRoss
2009-10-31 01:48:08
Thanks! Just remember to redirect the output to another directory (as in the awk solution).
Matt
2009-10-31 01:55:24
A:
This script works. I just tested it
===================
!/bin/bash
for i in ls .
#for each entry in the current directory
do
if test -e "$i" # if the entry is a file
then
#cat "$i" # cat the contents of the file to stdout
echo "\n" # print a newline to stdout
fi
done
===================
Hope this helps
inspectorG4dget
2009-10-31 02:04:18
no need ls, its useless.. secondly, you are using test -e, and since you are iterating a directory, it will cat a directory as well. a more appropriate flag to use for the test is -f , not -e
ghostdog74
2009-10-31 02:08:33
A:
Try
find . -type f -exec cat {} \; -exec echo "-- spacer --" \;
Obviously, the 'spacer' can be more than the simple example used here.
pavium
2009-10-31 02:06:12