bash 匹配后替换行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20464726/
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
Replace line after match
提问by Steven Penny
Given this file
鉴于此文件
$ cat foo.txt AAA 111 BBB 222 CCC 333
I would like to replace the first line after BBB
with 999
. I came up with this command
我想BBB
用999
. 我想出了这个命令
awk '/BBB/ {f=1; print; next} f {=999; f=0} 1' foo.txt
but I am curious to any shorter commands with either awk or sed.
但我对 awk 或 sed 的任何更短的命令感到好奇。
回答by Jotne
This is some shorter:
这是一些更短的:
awk 'f{sed '/BBB/!b;n;c999' file
="999";f=0}/BBB/{f=1}1' file
f {$0="999";f=0}
if f
is true, set line to 999
and f
to 0
/BBB/ {f=1}
if pattern match set f
to 1
1
print all lines, since 1
is always true.
f {$0="999";f=0}
如果f
是真的,集线999
,并f
以0
/BBB/ {f=1}
如果模式匹配集f
来1
1
打印所有行,因为1
始终是真实的。
回答by potong
This might work for you (GNU sed)
这可能对你有用(GNU sed)
$ awk '{print (f?999:sed '/BBB/{n;s/.*/999/}'
); f=0} /BBB/{f=1}' file
AAA
111
BBB
999
CCC
333
If a line contains BBB
, print that line and then change the following line to 999
.
如果一行包含BBB
,则打印该行,然后将下一行更改为999
。
!b
negates the previous address (regexp) and breaks out of any processing, ending the sed commands, n
prints the current line and then reads the next into the pattern space, c
changes the current line to the string following the command.
!b
否定前一个地址 (regexp) 并中断任何处理,结束 sed 命令,n
打印当前行,然后将下一行读入模式空间,c
将当前行更改为命令后面的字符串。
回答by Ed Morton
awk '/BBB/{print;getline;sed 's/\(BBB\)/\
999/'
="999"}1' your_file
回答by ray
can use sed also, it's shorter
也可以使用 sed,它更短
##代码##回答by Vijay
回答by toph
works on mac
适用于 mac