首页 > 解决方案 > 在不同的行中查找和替换

问题描述

假设我有几行我必须在大括号内选择一个字符串,然后用它在几行后用它来替换它

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并替换destinationWORD 这样

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

标签: regexperlsed

解决方案


我担心您发明的输入数据,因为它似乎与您评论中的“答案”可以正确处理的任何内容都不接近。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

推荐阅读