sed replace last line matching pattern

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

    A two-pass solution for when buffering the entire input is intolerable:

    sed "$(sed -n /a/= file | sed -n '$s/$/ s,a,c,/p' )" file

    (the earlier version of this hit a bug with history expansion encountered on a redhat bash-4.1 install, this way avoids a $!d that was being mistakenly expanded.)

    A one-pass solution that buffers as little as possible:

    sed '/a/!{1h;1!H};/a/{x;1!p};$!d;g;s/a/c/'
    

    Simplest:

    tac | sed '0,/a/ s/a/c/' | tac
    

提交回复
热议问题