且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用awk打印除匹配范围模式以外的所有内容

更新时间:2022-05-17 00:22:54

您刚刚举了一个棘手的(我不知道我应该称其为好还是坏^ _ ^)示例.您的文本具有完全相同的startpatternendpattern(#)

you just gave a tricky (I don't know I should call it good or bad ^_^ ) example. Your text have exactly same startpattern and endpattern (#)

我想您正在寻找与sed '/#/,/#/d'sed -n '/#/,/#/!p'

awk中有一些类似(与sed不同)的地址模型.在手册页中有解释.我说的不一样,你的榜样是很好的.如果start == end awk的地址模型不起作用:

There is some similiar (not same as sed's) address model in awk. In man page there is explanation. I said not same, your example is good one. if start == end the address model for awk won't work:

kent$  echo "abd
hfdh
#  
fafa
deafa
123 
#
end"|awk '/#/,/#/{next}1'                                                                                                                                                   
abd
hfdh
fafa
deafa
123 
end

因为awk匹配同一行(再次检查手册页),但是如果它们不同,请参见以下示例:

because awk matches the same line (again check man page) but if they are different, see this example:

kent$  echo "abd
hfdh
#  
fafa
deafa
123 
##
end"|awk '/#/,/##/{next}1'
abd
hfdh
end

它将提供您想要的.因此,在这种情况下,您可以这样做:

it will give what you want. so if this is the case, you could just do:

awk '/start/,/end/{next}1'

是的,与sed的非常相似.

yes, quite similar as sed's one.

如果开始和结束确实相同,则要使用awk进行操作,则需要标记.

If the start and end are really same, you want to do it with awk, you need flag.

kent$  echo "abd
hfdh
#  
fafa
deafa
123 
#
end"|awk '/#/&&!f{f=1;next}f&&/#/{f=0;next}!f'
abd
hfdh
end

好吧,例如更好地使用^#$,但这不是重点.我希望这能回答您的问题.

well, in example better use ^#$, but that is not the point. I hope this answers your question.