简体   繁体   English

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

[英]sed - Piping a string before the last line in a file

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. 我注意到当我添加任何字符串为'$i foo' ,“foo”会在正确的位置打印,但我希望打印管道线。

How can I use STDIN instead of "foo"? 我怎样才能使用STDIN而不是“foo”?

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

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

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:此解决方案受到保护,不受shell注入攻击

CON: This is a GNU sed specific answer. CON:这是一个GNU sed特定的答案。 So it may not be portable. 所以它可能不便携。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM