代码之家  ›  专栏  ›  技术社区  ›  user44556

用Perl替换多行搜索

  •  87
  • user44556  · 技术社区  · 17 年前

    我知道这种问题以前已经被问过很多次了。我再次来到这里的原因是,我觉得我错过了一些简单而基本的东西。

    #!/bin/perl -w -0777
    
    local $/ = undef;
    
    open INFILE, $full_file_path or die "Could not open file. $!";
    $string =  <INFILE>;
    close INFILE;
    
    $string =~ s/START.*STOP/$replace_string/sm;
    
    open OUTFILE, ">", $full_file_path or die "Could not open file. $!";
    print OUTFILE ($string);
    close OUTFILE;
    
    6 回复  |  直到 17 年前
        1
  •  113
  •   Community Mohan Dere    9 年前

    perl -i -pe 's/START.*STOP/replace_string/g' file_to_change
    

    thread 。要处理多行搜索,请使用以下命令-

    perl -i -pe 'BEGIN{undef $/;} s/START.*STOP/replace_string/smg' file_to_change
    

    为了将以下代码从单行代码转换为perl程序,请查看 perlrun documentation .

    如果你真的发现需要将其转换为可工作的程序,那么就让Perl为你处理文件的打开/关闭。

    #!/usr/bin/perl -pi
    #multi-line in place substitute - subs.pl
    use strict;
    use warnings;
    
    BEGIN {undef $/;}
    
    s/START.*STOP/replace_string/smg;
    

    然后,您可以使用文件名作为第一个参数调用脚本

    $perl subs.pl file_to_change
    

        2
  •  98
  •   Beejor    9 年前

    perl -0pe 's/search/replace/gms' file

    没有 -0 line-by-line ,这会导致多行搜索失败。

        3
  •  2
  •   Community Mohan Dere    9 年前

    考虑到您使用以下命令来抓取文件的全部内容:

    local $/ = undef;
    
    open INFILE, $full_file_path or die "Could not open file. $!";
    $string =  <INFILE>;
    close INFILE;
    

    然后用 $string ,处理文件的方式和处理内容的方式之间没有联系。如果在完成读取之前打开文件进行写入,则会出现问题,因为打开文件进行写操作会创建一个新文件,丢弃之前的内容。

    如果你想做的只是保存打开/关闭语句,那么就按照以下步骤操作 Jonathan Leffer suggested

        4
  •  0
  •   Samuel Liew cicero lopes    6 年前

    • 执行多个搜索替换或查询搜索替换操作
    • 可选择在段落模式下运行(用于多行搜索/替换)
    • 交互模式
    • 批处理模式
    • 可选择备份文件和备份编号
    • 忽略符号链接、空文件、写保护文件、套接字、命名管道和目录名

    https://github.com/tilo/replace_string

        5
  •  0
  •   Yordan Georgiev    4 年前

    bash脚本+perl-pi-e的组合是无与伦比的,这是bash函数直接在EOF标签前键入搜索和替换字符串的一个例子:

    # usage put into foobar.sh file, source foobar.sh file
    # call directly into the shell do_multiline_srch_and_replace
    do_multiline_srch_and_replace(){
    
                    test -z $dir_to_work && {
             echo "You must export dir_to_work=<<the-dir>> - it is empty !!!"; exit 1;
          }
                    test -d $dir_to_work || {
             echo "The dir to work on: \"$dir_to_work\" is not a dir !!!"; exit 1;
          }
    
                    echo "INFO dir_to_work: $dir_to_work" ; sleep 1
                    echo "INFO START :: searching and replacing in the non-binary files only"
    
                    while read -r file ; do (
                            echo "DEBUG working on the following file: $file"
    
             # those pattern in the file names we want to skip usually - git, not , py files
             case "$file" in
                *.git*)
                continue ;;
                *node_modules*)
                continue ;;
                *.venv*)
                continue ;;
             esac
             # note the string should be exactly between the s|| and the replace str between the ||gs
             # the 'EOF' guarantees that no special chars from the shell will affect the result
                            perl -pi - <<'EOF' "$file"
    BEGIN{undef $/;}
    s|a multiline
    string|the multiline
    string to replace|gs
    EOF
                    );
                    done < <(find $dir_to_work -type f -not -exec file {} \; | grep text | cut -d: -f1)
    
                    echo "INFO STOP  :: search and replace in non-binary files"
    
    }
    
        6
  •  0
  •   user3008410    3 年前

    我知道这个问题已经得到了回答,但这就是我解决这个问题的方法。

    假设您想更改一个UUID,但上面一行必须有匹配项,因为您有许多属于其他事物的UUID。

    _UUID=$(uuidgen | sed 's/-//g')
    export _UUID
    perl -0777 -pi.back -e 's/(<stringProp\sname="Argument\.name">_BINARYVIDEOTEMPURL<\/stringProp>\n.*<stringProp\sname="Argument\.value">)[a-zA-Z0-9]{32}(<\/stringProp>)/$1$ENV{_UUID}$2/g;' test.txt
    

    你的test.txt文件读起来是这样的:(我知道这不是一个有效的XML,但只是创建它)

    <?xml version="1.0" encoding="UTF-8"?> <jmeterTestPlan version="1.2" properties="5.0" jmeter="5.2.1">
      <hashTree>
    <TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="K8S Load Test Plan" enabled="true">      
      <stringProp name="TestPlan.user_define_classpath"></stringProp>
    </TestPlan>
          <collectionProp name="Arguments.arguments">
            <elementProp name="_SESSIONID" elementType="Argument">
              <stringProp name="Argument.name">_SESSIONID</stringProp>
              <stringProp name="Argument.value">7c096b65-84b6-40c9-be93-a5891ec0394d</stringProp>
              <stringProp name="Argument.metadata">=</stringProp>
            </elementProp>
            <elementProp name="_BINARYVIDEOTEMPURL" elementType="Argument">
              <stringProp name="Argument.name">_BINARYVIDEOTEMPURL</stringProp>
              <stringProp name="Argument.value">64e1886127fa41c4a58e59fe2bb098e1</stringProp>
              <stringProp name="Argument.metadata">=</stringProp>
            </elementProp>
          </collectionProp>
    

    • 多线向前和向后看。我无法告诉你perl是如何工作的。
    • -pi.back基本上是内联编辑和备份文件。
    • -e基本上是's/repealcethis/withhis/g',但它包含正则表达式 需要新的线路来匹配。此外,它还展示了如何使用环境变量和分组来重新创建字符串。

    不管怎样,希望这能帮助到别人。