[ACCEPTED]-Bash: concatenate multiple files and add "\newline" between each?-cat

Accepted answer
Score: 10

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

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

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

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

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

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

Score: 5

You can do:

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

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

Score: 1

Here's a funny possibility, using ed, the 4 standard editor:

ed -s < <(
    for f in *.md; do
        [[ $f = output.md ]] && continue
        printf '%s\n' "r $f" a '\newline' .
    printf '%s\n' "w output.md" "q"

(I've inserted a line to 3 exclude output.md from the inserted files).

For each 2 file:

  • r $f: r is ed's insert file command,
  • a: ed starts a newline after the current line for editing,
  • \newline: well, we're insertion mode, so ed just inserts this,
  • .: to stop insert mode.

At the end, we write the buffer to the 1 file output.md and quit.

More Related questions