使用 sed
我 read您可以替换以第二个开头的所有匹配项
You can combine a number with the g (global) flag. For instance, if you want to leave the first word alone, but change the second, third, etc. to be DELETED instead, use /2g:
示例
sed 's/foo/bar/2g' a.txt
但是,如何替换直到第二个匹配项,以便第三个、第四个等不受影响?类似的东西
sed 's/foo/bar/1-2' a.txt
最佳答案
这可能对你有用(GNU sed):
sed 's/foo/&\n/2;T;h;s//bar/g;G;s/\n.*\n//' file
将第 n 次出现的目标字符串替换为其自身和换行符。 如果替换失败则退出,否则将模式空间 (PS) 复制到保留空间 (HS)。 使用替换字符串进行替换,然后使用更改后的行重新构建原始行。
另外:
sed 's/foo/\n/g;s/\n/foo/3g;s/\n/bar/g' file
其中使用第n+1而不是第1到第n
关于bash - 替换最多第 n 个匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15043789/