我有一个包含以下内容的文件作为示例
cat test.log
hello
how are you?
terminating
1
2
3
terminating
1
2
当我使用 grep 命令在终止后显示输出时,它显示如下。
sed -n '/terminating/,$p' test.log
terminating
1
2
3
terminating
1
2
我想要输出如下
terminating
1
2
有人可以帮我吗?
sed的代码:
$ sed -n '/终止/{N;N;h};${g;p}' 文件
终止
1
2
如果行匹配terminating,将它和接下来的两行存储在保持空间中。在 上打印三行$EOF。
带有sed脚本的示例:
$ 猫脚本.sed
/终止/{
ñ
ñ
H
}
${
G
p
}
$ sed -nf script.sed 文件
终止
1
2
对于最后一行之后的所有行terminating:
$猫文件
猫测试.log
你好
你好吗?
终止
1
2
3
终止
1
2
3
4
5
6
$ 猫脚本.sed
H
/终止/{
H
}
${
G
p
}
$ sed -nf script.sed 文件
终止
1
2
3
4
5
6
这可能对您有用(GNU sed):
sed -r '/^terminating/!d;:a;$!N;/.*\n(terminating)/s//\1/;$q;ba' file
除非该行以terminating丢弃它开头。阅读更多行,丢弃行开头的任何行terminating。在文件末尾打印出文件的其余部分。
sed -n 'H;/terminating/x;${x;p}' test.log
作为带注释的伪代码:
for each line:
append the line to the hold space H
if line matches /terminating/ /terminating/
then set hold space to line x
on the last line: $
get the hold space x
and print p
注意:x实际上交换保持/模式空间。