How to print out the last patterns range using awk?

隐身守侯 提交于 2020-03-14 05:00:28

问题


My file is like this:

/begin pattern/
first match
/end pattern/

other text

/begin pattern/
second match
/end pattern/

other text

/begin pattern/
This is the one I want to print out
/end pattern/
other text

How can I print out the last match using awk? I just know about how to print out all these matches.


回答1:


awk 'END { print r } 
/end pattern/ { f = x }
/begin pattern/ { f = 1; r = x }
f++ > 1 { r = r ? r RS $0 : $0 }
' infile 



回答2:


Depending on if you want the lines containing the delimiters printed or not:

$ awk '
    /begin pattern/ { rec=""; f=1 }
    f { rec=rec $0 ORS; if (/end pattern/) {last=rec; f=0} }
    END { printf "%s", last }
' file
/begin pattern/
This is the one I want to print out
/end pattern/

or:

$ awk '
    f { if (/end pattern/) {last=rec; f=0} rec=rec $0 ORS }
    /begin pattern/ { rec=""; f=1 }
    END { printf "%s", last }
' file
This is the one I want to print out

That ensures that what you print is a block starting with begin pattern and ending with end pattern so you don't just print a bunch of lines following a start pattern with no end pattern if such exists at the end of your input file. It also ensures you don't print a blank line if no matching block exists in the input.




回答3:


Store the current match and use the END block to print it out:

awk '/end pattern/{flag=0} flag{m=$0} /begin pattern/{flag =1}  END{print m}' file

This works if there is only one line between /begin pattern/ and /end pattern/.



来源:https://stackoverflow.com/questions/4448626/how-to-print-out-the-last-patterns-range-using-awk

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!