首页 > 解决方案 > 正则表达式:仅在不以单词开头时才替换短语

问题描述

我正在尝试用 perl 命令行替换文本文件中的某些短语(“我的术语”)。这些文件按部分划分,如下所示:

section1
my term
nothing abc

section2
some text
my term
another text

section3
some text
my term

section4
some text
my term

某些部分可能不存在。我想要实现的是用“其他术语”替换“我的术语”,但前提是它在第 1 节中。我尝试了一些前瞻和后视语法,但找不到可行的解决方案(https://regex101.com/r/mfqay6/1

例如,如果我删除第 1 节,则以下代码匹配,而我不想要它:

(?!section2).*(my term)

有什么帮助吗?

标签: regexperlregex-lookarounds

解决方案


一个简单的衬里:

perl  -ane 's/my term/some other term/ if(/section1/ ... /section/);print' file.txt 

输出:

section1
some other term
nothing abc

section2
some text
my term
another text

section3
some text
my term

section4
some text
my term

推荐阅读