Bash:连接多个文件并在每个文件之间添加“\newline”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23815120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 10:30:52  来源:igfitidea点击:

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

bashfilecat

提问by pimpampoum

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

我有一个小的 Bash 脚本,它获取一个目录的所有 Markdown 文件,并将它们合并为一个,如下所示:

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:

它运作良好。现在我想在每个文档之间添加字符串“\newline”,如下所示:

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

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

我怎样才能做到这一点?上面的代码显然不起作用。

回答by Tom Fenech

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

如果你想要文字 string "\newline",试试这个:

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

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

这假设output.md不存在。如果确实如此(并且您想将其内容包含在最终输出中),您可以执行以下操作:

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.

这可以防止错误cat: output.md: input file is output file

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

如果你想覆盖它,你应该rm在开始之前。

回答by jaypal singh

You can do:

你可以做:

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

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

您可以添加一个echo命令来添加换行符。为了提高性能,我建议将写入移动到循环>之外,for以防止在每次迭代时读取和写入文件。

回答by gniourf_gniourf

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

这是一个有趣的可能性,使用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"
)

(I've inserted a line to exclude output.mdfrom the inserted files).

(我插入了一行以output.md从插入的文件中排除)。

For each file:

对于每个文件:

  • r $f: ris ed's insert filecommand,
  • a: edstarts a newline after the current line for editing,
  • \newline: well, we're insertion mode, so edjust inserts this,
  • .: to stop insert mode.
  • r $f: rised插入文件命令,
  • a:ed在当前行之后开始换行以进行编辑,
  • \newline: 好吧,我们是插入模式,所以ed只需插入这个,
  • .: 停止插入模式。

At the end, we write the buffer to the file output.mdand quit.

最后,我们w将缓冲区写入文件output.mdquit。