例如:我唯一的目标是在比赛中进球
My only goal is to score a jinx in the match
两个单词之间应该有一个或多个单词。
最佳答案
$ echo "My only goal is to score a goal in the match" | \
sed -r 's/(\b\w+\b)(.*\w+.*)\1/\1\2jinx/g'
My only goal is to score a jinx in the match
-r
激活扩展 posix regular expressions 。注意:使用基本的 posix 正则表达式,您必须转义括号,例如:\(....\)
并且+
运算符不存在(\b\w+\b)
匹配单词(.*\w+.*)
捕获其间的所有内容\1
匹配第一个括号,\2
匹配第二个括号g
代表全局,没有这个它只会改变第一个匹配
因此,(\b\w+\b)(.*\w+.*)\1/
会发现同一单词的行出现了两次
然后 \1\2jinx
会将第二次出现的 \1
替换为 jinx
关于regex - 如果一行有 2 个相同的单词,则使用 sed 将第二个单词更改为 'jinx',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53532553/