sed replace last line matching pattern

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

    tac infile.txt | sed "s/a/c/; ta ; b ; :a ; N ; ba" | tac

    The first tac reverses the lines of infile.txt, the sed expression (see https://stackoverflow.com/a/9149155/2467140) replaces the first match of 'a' with 'c' and prints the remaining lines, and the last tac reverses the lines back to their original order.

提交回复
热议问题