regex - 正则表达式:仅在不以单词开头时才替换短语
问题描述
我正在尝试用 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)
有什么帮助吗?
解决方案
一个简单的衬里:
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
推荐阅读
- java - 如何从 url Android Studio 下载我的位图到画廊
- java - 从 CompletableFuture 线程中的主线程访问 SessionScoped bean 不起作用
- ionic-framework - 应用程序最小化离子科尔多瓦插件在 iONIC5 应用程序中不起作用
- c++ - 在链表类中实现 removeDuplicates() 方法
- csv - 如何按年月日创建 HDFS 目录?
- typescript - 未找到 v-data-table 组件
- android - 音频文件中的语音到文本 (Android)
- vue.js - 在 vue2-editor 中处理粘贴事件
- c - 调用 FreeLibrary 后 DLL 仍然被锁定
- r - 创建一个*只读* CSV