sed replace last line matching pattern

后端 未结 14 2123
暗喜
暗喜 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:01

    Given:

    $ cat file
    a
    b
    a
    b
    

    You can use POSIX grep to count the matches:

    $ grep -c '^a' file
    2
    

    Then feed that number into awk to print a replacement:

    $ awk -v last=$(grep -c '^a' file) '/^a/ && ++cnt==last{ print "c"; next } 1' file
    a
    b
    c
    b
    

提交回复
热议问题