sed replace last line matching pattern

后端 未结 14 2083
暗喜
暗喜 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.
    0 讨论(0)
  • 2020-12-11 02:22

    Here is a way with only using awk:

    awk '{a[NR]=$1}END{x=NR;cnt=1;while(x>0){a[x]=((a[x]=="a"&&--cnt==0)?"c <===":a[x]);x--};for(i=1;i<=NR;i++)print a[i]}' file
    
    $ cat f
    a
    b
    a
    b
    f
    s
    f
    e
    a
    v
    $ awk '{a[NR]=$1}END{x=NR;cnt=1;while(x>0){a[x]=((a[x]=="a"&&--cnt==0)?"c <===":a[x]);x--};for(i=1;i<=NR;i++)print a[i]}' f
    a
    b
    a
    b
    f
    s
    f
    e
    c <===
    v
    
    0 讨论(0)
提交回复
热议问题