perl regex not matching string with newline character \n

前端 未结 2 1949
孤城傲影
孤城傲影 2020-12-19 11:00

I\'m trying to use perl (v5.14.2) via a bash shell (GNU Bash-4.2) in Kubuntu (GNU/Linux) to search and replace a string that includes a newline character, but I\'m not succe

相关标签:
2条回答
  • 2020-12-19 11:12

    Try doing this, I make this possible by modifying the input record separator (a newline by default) :

    perl -i -p00e 's,hello\nkitty,newtext,' prac1.html
    

    from perldoc perlrun :

    -0[octal/hexadecimal]

    specifies the input record separator ($/ ) as an octal or hexadecimal number. If there are no digits, the null character is the separator. Other switches may precede or follow the digits. For example, if you have a version of find which can print filenames terminated by the null character, you can say this:

    find . -name '*.orig' -print0 | perl -n0e unlink
    

    The special value 00 will cause Perl to slurp files in paragraph mode. Any value 0400 or above will cause Perl to slurp files whole, but by convention the value 0777 is the one normally used for this purpose.

    0 讨论(0)
  • 2020-12-19 11:30

    The problem is that "-p" has already implicitly wrapped this loop around your "-e", and the "<>" is splitting the input into lines, so your regexp never gets a chance to see more than one line.

     LINE:
           while (<>) {
               ...             # your program goes here
           } continue {
               print or die "-p destination: $!\n";
           }
    

    See the perlrun manpage for more information.

    0 讨论(0)
提交回复
热议问题