开发者

How to print out the last patterns range using awk?

My file is like this:

/begin pattern/

first match

/end pattern/

other text

/begin pattern/

second match

/end p开发者_开发问答attern/

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.


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.


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


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/.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜