bash - 替换最多第 n 个匹配项

标签 bash sed

使用 sedread您可以替换以第二个开头的所有匹配项

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/

相关文章:

bash - 如何使 'cut' 命令将相同的连续定界符视为一个?

linux - 仅使用 GNU sed 在第一个匹配项上插入时出现问题

bash - 使用 sed/awk 打印具有匹配模式或另一个匹配模式的行

python - 如何将变量参数从 bash 脚本传递到 python 脚本

bash - 从 shell 脚本的行数中提取公共(public)部分文本

bash - 在不终止的情况下运行 xterm -e

linux - 我想在从文件创建的每个用户名末尾添加 2 个随机数。我将如何在 bash 中执行此操作?

awk - 使用sed删除除结束模式以外的行范围

Linux 替换换行符

regex - 使用 sed 更改找到的模式中的任意数量的分隔符