Print last matching line?

后端 未结 5 769
無奈伤痛
無奈伤痛 2021-01-14 08:20

Using awk, I would like to print the last matching line of a file. I would like only the matching line itself, not any range of lines. I can use a command like

相关标签:
5条回答
  • 2021-01-14 08:43

    You can assign values to variables and print them at the end of processing both the lines and their number.

    File:

    $ cat file
    foo1
    foo2
    foo3
    4
    5
    

    Command:

    $ awk '/foo/ {a=$0;n=NR} END{print n, a}' file
    3 foo3
    
    0 讨论(0)
  • 2021-01-14 08:44

    The command tail allows you to retreive the last n lines of an input stream. You can pipe your awk output into tail in order to trim off everything except the last line:

    awk '/foo/' bar.txt | tail -1
    
    0 讨论(0)
  • 2021-01-14 08:53

    sed solution:

    sed -n '/foo/h;$!b;g;p' bar.txt
    

    Place the matching regex in hold buffer and branch out. Keep doing this until end of file. When the end of file is reached, grab the line from hold space and place it on pattern space. Print pattern space.

    0 讨论(0)
  • 2021-01-14 08:53

    reverse the file and find the first match.

    tac file | awk '/foo/ {print; exit}'
    
    0 讨论(0)
  • 2021-01-14 09:02

    You can save the value in a variable and then print it after processing the whole file:

    awk '/foo/ {a=$0} END{print a}' file
    

    Test

    $ cat file
    foo1
    foo2
    foo3
    4
    5
    $ awk '/foo/ {a=$0} END{print a}' file
    foo3
    
    0 讨论(0)
提交回复
热议问题