Using GNU sed
:
sed -s -e $'$a\\\n' ./*.txt >concat.out
This concatenates all data to concat.out
while at the same time appending an empty line to the end of each file processed.
The -s
option to GNU sed
makes the $
address match the last line in each file instead of, as usual, the last line of all data. The a
command appends one or several lines at the given location, and the data added is a newline. The newline is encoded as $'\n'
, i.e. as a "C-string", which means we're using a shell that understands these (like bash
or zsh
). This would otherwise have to be added as a literal newline:
sed -s -e '$a\
' ./*.txt >concat.out
Actually, '$a\\'
and '$a\ '
seems to work too, but I'm not entirely sure why.
This also work, if one thinks the a
command is too bothersome to get right:
sed -s -e '${p;g;}' ./*.txt >concat.out
Any of these variation would insert an empty line at the end of the output of the last file too. If this final newline is not wanted, deletede it by passing the overall result through sed '$d'
before redirecting to your output file:
sed -s -e '${p;g;}' ./*.txt | sed -e '$d' >concat.out
cat
implementations will give you that input file is output file. Some others will happily run here potentially causing an infinite loop that fills up the filesystem. – Stéphane Chazelas Jan 11 '21 at 15:36[[ "$f" = "newfile.txt" ]]
is a kshism. POSIXly, you'd use[ "$f" = newfile.txt ]
. – Stéphane Chazelas Jan 11 '21 at 15:38cat
issue? I always thought it was the shell, notcat
. Then why doesn'tcat file1 file2 > file1
complain? As for the quotes, thanks fixed. Having unquoted strings feels weird to me. – terdon Jan 11 '21 at 15:45cat file > file
, I suppose yourcat
detectsfile
is empty and does nothing instead of reporting an error. Solariscat
still reports an error there. Note how the error message starts withcat:
. I can't see how the shell could detect the condition. – Stéphane Chazelas Jan 11 '21 at 15:50( echo foo> newfile.txt; cat newfile.txt; ) > newfile.txt
while this does not( cat newfile.txt ) > newfile.txt
. So mycat
(GNU coreutils, 8.32) seems to detect that the file is empty and doesn't complain in the second one. TIL, thanks! – terdon Jan 11 '21 at 16:01