Bash: merge multiple files and add "\ newline" between them?

I have a small Bash script that takes all the Markdown files of a directory and merges them into one, for example:

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

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

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

How can i do this? The above code is clearly not working.

+4
source share
3 answers

If you need a literal string "\newline", try the following:

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

This suggests that output.mddoes not yet exist. If so (and you want to include its contents in the final output), you can do:

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

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

, , , rm.

+8

:

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

echo, . , > for, .

+4

, ed, :

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

( , output.md ).

:

  • r $f: r ed ,
  • a: ed ,
  • \newline: , , ed ,
  • .: .

w output.md q uit.

0

Source: https://habr.com/ru/post/1541669/


All Articles