bash sed - 在文件的最后一行之前用管道输送一个字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26120345/
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
sed - Piping a string before the last line in a file
提问by Tarek Eldeeb
I have a command that prints a single line. I want to add/pipe this line to a file, just above its last line.
我有一个打印单行的命令。我想将此行添加/管道到文件,就在其最后一行的上方。
my_cmd | sed -i '$i' test
I just find an empty line in the correct place, above the last line.
I notice that when I add any string as '$i foo'
, the "foo" gets printed in the correct place, but I want the piped line to be printed.
我只是在最后一行上方的正确位置找到了一个空行。我注意到当我添加任何字符串 as 时'$i foo'
,“foo”会打印在正确的位置,但我希望打印管道线。
How can I use STDIN instead of "foo"?
如何使用 STDIN 而不是“foo”?
回答by Kent
this should do the trick:
这应该可以解决问题:
sed -i "$i $(cmd)" file
test:
测试:
kent$ cat f
1
2
3
4
5
kent$ sed -i "$i $(date)" f
kent$ cat f
1
2
3
4
Tue Sep 30 14:10:02 CEST 2014
5
回答by Josh Jolly
Instead of passing your output to sed
via pipe, you can use command substitution instead:
sed
您可以使用命令替换,而不是通过管道将输出传递给:
$ cat f
First line
Second line
Third line
$ sed -i '$i'"$(echo 'Hello World')" f
$ cat f
First line
Second line
Hello World
Third line
So in your case you can use:
因此,在您的情况下,您可以使用:
sed -i '$i'"$(my_cmd)" test
回答by anishsane
The other answers should work too.
其他答案也应该有效。
Here is another approach, which uses a syntax similar to your code snippet and is free from shell injection exploits.
这是另一种方法,它使用类似于您的代码片段的语法,并且不受 shell 注入漏洞的影响。
$ seq 1 5 > test.input
$ echo hello/world | sed '${x;s/.*/cat/e;p;x}' test.input
1
2
3
4
hello/world
5
PRO: This solution is protected from shell injection exploits.
PRO:此解决方案不受外壳注入漏洞的影响。
CON: This is a GNU sed specific answer. So it may not be portable.
缺点:这是一个 GNU sed 特定的答案。所以它可能不便携。