sed替换文件中第二次出现不起作用

sed replace second occurrence in file not working

我正在使用 centos 7.sed 命令来替换 second 事件对我不起作用。 我尝试了以下解决方案 - Sed/Awk to delete second occurence of string - platform independent https://unix.stackexchange.com/questions/18303/sed-delete-all-occurrences-of-a-string-except-the-first-one

文件-

this
foo
is
a test
file
this
foo

我正在尝试 运行 -

sed 's/foo/bar/2g' file
sed 's/foo/bar/2' file
sed -i 's/foo/bar/2g' file

我希望用第二个中的“bar”替换所有出现的“foo”。

这将对包含指定模式 (/foo/) 的第二行和所有后续行执行替换:

sed ':1; /foo/! { n; b1 }; :2; n; s/foo/bar/; b2' file

它有两部分:

  • :1; /foo/! { n; b1 }; 是一个循环,读取行并输出不变,直到遇到第一个匹配 /foo/.
  • 的行
  • :2; n; s/foo/bar/; b2是一个循环,重复输出当前行,读取下一行并执行替换s/foo/bar/。对于不包含该模式的行,替换是无害的空操作。

模式的第一个匹配项是第二个循环开头的当前行,因此当第二个循环首次执行其 n 命令时,它的输出不变。

这可能适合您 (GNU sed):

sed -z 's/foo/bar/2' file

将整个文件插入模式 space 并将第二次出现的 foo 替换为 bar

选择:

sed 'H;$!d;x;s/.//;s/foo/bar/2' file