sed replace last line matching pattern

后端 未结 14 2087
暗喜
暗喜 2020-12-11 01:45

Given a file like this:

a
b
a
b

I\'d like to be able to use sed to replace just the last line that contains an instance of \"a

14条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-11 02:21

    awk-only solution:

    awk '/a/{printf "%s", all; all=$0"\n"; next}{all=all $0"\n"} END {sub(/^[^\n]*/,"c",all); printf "%s", all}' file
    

    Explanation:

    • When a line matches a, all lines between the previous a up to (not including) current a (i.e. the content stored in the variable all) is printed
    • When a line doesn't match a, it gets appended to the variable all.
    • The last line matching a would not be able to get its all content printed, so you manually print it out in the END block. Before that though, you can substitute the line matching a with whatever you desire.

提交回复
热议问题