regex - 在不同的行中查找和替换
问题描述
假设我有几行我必须在大括号内选择一个字符串,然后用它在几行后用它来替换它
Here is the word that I need to select in braces (WORD)
Second line
Third line
Forth line
Path where I want it to replace /root/usr/destination/
few more lines
我想选择WORD
并替换destination
成WORD
这样
Here is the word that I need to select in braces (WORD1)
Second line
Third line
Forth line
Path where I want it to replace /root/usr/WORD1/
few more lines
Also how can I do this for tis to be recurring in a same file
Here is the word that I need to select in braces (WORD2)
Second line
Third line
Forth line
Path where I want it to replace /root/usr/WORD2/
few more lines
Here is another word that I need to select in braces (WORD3)
Second set of lines
Third line
Forth line
Path where I want it to replace /root/usr/WORD3/
few more lines and pattern repeats like this so on
解决方案
我担心您发明的输入数据,因为它似乎与您评论中的“答案”可以正确处理的任何内容都不接近。DATA
但是,这是一个从完整文件句柄读取的解决方案。我一次读了一行文件,而不是一口吞下整个文件,因为这样更容易找到新的替换字符串
唯一的其他附带条件是
destination
关键字永远不会出现在同一行的替换词之前无需区分
destination
路径字符串中的出现除了替换词周围的括号外,输入文本中没有括号
use strict;
use warnings 'all';
my $rep;
while ( <DATA> ) {
$rep = $1 if /\(([^()]+)\)/;
s/destination/$rep/g if defined $rep;
print;
}
__DATA__
Here is the word that I need to select in braces (WORD1)
Second line
Third line
Forth line
Path where I want it to replace /root/usr/destination/
few more lines
Here is the word that I need to select in braces (WORD2)
Second line
Third line
Forth line
Path where I want it to replace /root/usr/destination/
few more lines
Here is the word that I need to select in braces (WORD3)
Second line
Third line
Forth line
Path where I want it to replace /root/usr/destination/
few more lines
输出
Here is the word that I need to select in braces (WORD1)
Second line
Third line
Forth line
Path where I want it to replace /root/usr/WORD1/
few more lines
Here is the word that I need to select in braces (WORD2)
Second line
Third line
Forth line
Path where I want it to replace /root/usr/WORD2/
few more lines
Here is the word that I need to select in braces (WORD3)
Second line
Third line
Forth line
Path where I want it to replace /root/usr/WORD3/
few more lines
虽然我建议不要使用它们,但它的单线版本是
perl -pe '$rep = $1 if /\(([^()]+)\)/; s/destination/$rep/g if defined $rep;' myfile
推荐阅读
- autodesk-forge - Autodesk Forge 查看器标记大文本被截断
- augmented-reality - 水上增强现实
- javascript - 测试使用 useEffect 钩子和 apollo 的自定义上下文钩子
- python-3.x - 查找元组列表的最大聚合
- c# - 无法调整外部窗口的大小
- css - 闪亮的 sliderTextInput 使所有文本标签可见
- java - 如何使用 DateTimeFormatter 或 Java 中的任何其他库将“2019-07-14T18:30:00.000Z”转换为“2021-09-26 04:30:00 PM”
- ios - NFC NDEF 写入 IOS 编码
- amazon-web-services - AWS 控制台中的 AWS ElasticSearch 请求超时
- devexpress - 适用于 Blazor 的 DevExpress dxDataGrid -“当前电路存在未处理的异常”错误