sed replace last line matching pattern

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

    Many good answers here; here's a conceptually simple two-pass sed solution assisted by tail that is POSIX-compliant and doesn't read the whole file into memory, similar to Eran Ben-Natan's approach:

    sed "$(sed -n '/a/ =' file | tail -n 1)"' s/a/c/' file
    
    • sed -n '/a/=' file outputs the numbers of the lines (function =) matching regex a, and tail -n 1 extracts the output's last line, i.e. the number of the line in file file containing the last occurrence of the regex.

    • Placing command substitution $(sed -n '/a/=' file | tail -n 1) directly before ' s/a/c' results in an outer sed script such as 3 s/a/c/ (with the sample input), which performs the desired substitution only on the last on which the regex occurred.

    If the pattern is not found in the input file, the whole command is an effective no-op.

提交回复
热议问题