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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 08:56:04  来源:igfitidea点击:

Replace line after match

bashsedawk

提问by Steven Penny

Given this file

鉴于此文件

$ cat foo.txt
AAA
111
BBB
222
CCC
333

I would like to replace the first line after BBBwith 999. I came up with this command

我想BBB999. 我想出了这个命令

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 fis true, set line to 999and fto 0
/BBB/ {f=1}if pattern match set fto 1
1print all lines, since 1is always true.

f {$0="999";f=0}如果f是真的,集线999,并f0
/BBB/ {f=1}如果模式匹配集f1
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

!bnegates the previous address (regexp) and breaks out of any processing, ending the sed commands, nprints the current line and then reads the next into the pattern space, cchanges 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