在 Bash 中连接字符串、文件和程序输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10947722/
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
Concatenate strings, files and program output in Bash
提问by Boldewyn
The use case is, in my case, CSS file concatenation, before it gets minimized. To concat two CSS files:
在我的情况下,用例是 CSS 文件串联,然后它被最小化。连接两个 CSS 文件:
cat 1.css 2.css > out.css
To add some text at one singleposition, I can do
要在一个位置添加一些文本,我可以这样做
cat 1.css <<SOMESTUFF 2.css > out.css
This will end in the middle.
SOMESTUFF
To add STDOUT from oneother program:
要添加STDOUT一个其他程序:
sed 's/foo/bar/g' 3.css | cat 1.css - 2.css > out.css
So far so good. But I regularly come in situations, where I need to mix severalstrings, files and even program output together, like copyright headers, files preprocessed by sed(1)
and so on. I'd like to concatenate them together in as little steps and temporary files as possible, while having the freedom of choosing the order.
到现在为止还挺好。但是我经常遇到需要将多个字符串、文件甚至程序输出混合在一起的情况,例如版权标头、预处理的文件sed(1)
等等。我想以尽可能少的步骤和临时文件将它们连接在一起,同时可以自由选择顺序。
In short, I'm looking for a way to do this in as little steps as possible in Bash:
简而言之,我正在寻找一种在 Bash 中以尽可能少的步骤完成此操作的方法:
command [string|file|output]+ > concatenated
# note the plus ;-) --------^
(Basically, having a cat
to handle multiple STDINs would be sufficient, I guess, like
(基本上,有一个cat
处理多个标准输入就足够了,我想,就像
<(echo "FOO") <(sed ...) <(echo "BAR") cat 1.css -echo1- -sed- 2.css -echo2-
But I fail to see, how I can access those.)
但我看不到,我如何访问这些。)
回答by Paused until further notice.
This works:
这有效:
cat 1.css <(echo "FOO") <(sed ...) 2.css <(echo "BAR")
回答by Joni
You can add all the commands in a subshell, which is redirected to a file:
您可以在子shell中添加所有命令,该子shell被重定向到一个文件:
(
cat 1.css
echo "FOO"
sed ...
echo BAR
cat 2.css
) > output
You can also append to a file with >>
. For example:
您还可以附加到带有>>
. 例如:
cat 1.css > output
echo "FOO" >> output
sed ... >> output
echo "BAR" >> output
cat 2.css >> output
(This potentially opens and closes the file repeatedly)
(这可能会反复打开和关闭文件)
回答by nhahtdh
You can do:
你可以做:
echo "$(command 1)" "$(command 2)" ... "$(command n)" > outputFile