bash 如何将文字文本添加到 Unix 'cat' 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14883669/
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 04:34:22  来源:igfitidea点击:

How to add literal text to the Unix 'cat' command

bashcat

提问by incandescentman

I'm trying to catsome files together, while at the same time adding some text between files. I'm a Unix newbie and I don't have the hang of the syntax.

我想猫的一些文件一起,而在同一时间添加文件之间的一些文字。我是 Unix 新手,我不了解语法。

Here's my failed attempt:

这是我失败的尝试:

cat echo "# Final version (reflecting my edits)\n\n" final.md echo "\n\n# The changes I made\n\n" edit.md echo "\n\n#Your original version\n\n" original.md > combined.md

How do I fix this? Should I be using pipes or something?

我该如何解决?我应该使用管道还是什么?

采纳答案by Rohit

If I understand you, it should be something like:

如果我理解你,它应该是这样的:

echo "# Final version (reflecting my edits)\n\n" >> combined.md
cat final.md >> combined.md
echo "\n\n# The changes I made\n\n" >> combined.md
cat edit.md >> combined.md

And so on.

等等。

回答by chepner

Use a command group to merge the output into one stream:

使用命令组将输出合并为一个流:

{
   echo -e "# Final version (reflecting my edits)\n\n"
   cat final.md 
   echo -e "\n\n# The changes I made\n\n"
   cat edit.md 
   echo -e "\n\n#Your original version\n\n"
   cat original.md
} > combined.md

There are tricks you can play with process substitution and command substitution (see Lev Levitsky's answer) to do it all with one command (instead of the separate catprocesses used here), but this should be efficient enough with so few files.

您可以使用进程替换和命令替换(请参阅 Lev Levitsky 的回答)使用一个命令(而不是cat此处使用的单独进程)来完成所有操作,但这对于如此少的文件应该足够有效。

回答by Lev Levitsky

A process substitution seems to work:

进程替换似乎有效:

$ cat <(echo 'FOO') foo.txt <(echo 'BAR') bar.txt
FOO
foo
BAR
bar

You can also use command substitution inside a here-document.

您还可以在此处的文档中使用命令替换。

$ cat <<EOF
FOO
$(< foo.txt)
BAR
$(< bar.txt)
EOF