sed - 在文件的最后一行之前管道一个字符串

时间:2014-09-30 12:01:37

标签: linux bash redirect sed

我有一个打印单行的命令。 我想将此行/管道添加到文件中,就在最后一行的上方。

my_cmd | sed -i '$i' test

我只是在最后一行上方的正确位置找到一个空行。 我注意到当我添加任何字符串'$i foo'时," foo"在正确的地方打印,但我希望打印管道。

如何使用STDIN代替" foo"?

3 个答案:

答案 0 :(得分:10)

这应该可以解决问题:

 sed -i "\$i $(cmd)" file

试验:

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

答案 1 :(得分:6)

不是通过管道将输出传递给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

因此,在您的情况下,您可以使用:

sed -i '$i'"$(my_cmd)" test

答案 2 :(得分:3)

其他答案也应该有效。

这是另一种方法,它使用类似于您的代码片段的语法,并且没有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:此解决方案受shell injection exploits保护。

CON:这是一个GNU sed特定的答案。所以它可能不便携。