Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

file

bash

cat

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.

like image 771
pimpampoum Avatar asked May 22 '14 19:05

pimpampoum


2 Answers

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.

like image 179
Tom Fenech Avatar answered Oct 10 '22 17:10

Tom Fenech


You can do:

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

You can add an echo command to add a newline. To improve performance I would recommend to move the write > outside the for loop to prevent reading and writing of file at every iteration.

like image 45
jaypal singh Avatar answered Oct 10 '22 17:10

jaypal singh