Bash: concatenate multiple files and add "\newline" between each?

pimpampoum picture pimpampoum · May 22, 2014 · Viewed 7.2k times · Source

I have a small Bash script that takes all Markdown files of a directory, and merge them into one like this:

for f in *.md; do (cat "${f}";) >> output.md; done

It works well. Now I'd like to add the string "\newline" between each document, something like this:

for f in *.md; do (cat "${f}";) + "\newline" >> output.md; done

How can I do that? The above code obviously doesn't work.

Answer

Tom Fenech picture Tom Fenech · May 22, 2014

If you want the literal string "\newline", try this:

for f in *.md; do cat "$f"; echo "\newline"; done > output.md

This assumes that output.md doesn't already exist. If it does (and you want to include its contents in the final output) you could do:

for f in *.md; do cat "$f"; echo "\newline"; done > out && mv out output.md

This prevents the error cat: output.md: input file is output file.

If you want to overwrite it, you should just rm it before you start.