Perl command line multi-line replace

后端 未结 2 1084
慢半拍i
慢半拍i 2020-11-29 05:16

I\'m trying to replace text in a multi-line file using command-line perl. I\'m using Ubuntu Natty.

Below is the content of my text file (called test.txt):

         


        
2条回答
  •  醉酒成梦
    2020-11-29 06:02

    The -p switch causes Perl to iterate over every line of the input and execute the given code for each of them (and to print the lines afterwards). Specifically, the command

    perl -p -e 'SOME_CODE_HERE;'
    

    is exactly equivalent to running the following Perl program:

    LINE: while (<>) {
        SOME_CODE_HERE;
    } continue {
        print or die "-p destination: $!\n";
    }
    

    Your regexp seems to be intended to match multiple lines at once, which obviously won't work if Perl is processing the input line by line. To make it work as intended, you have (at least) two options:

    1. Change Perl's notion of what constitutes a line by using the -0NNN switch. In particular, the switch -0777 causes Perl to treat every input file as a single "line".

    2. Rewrite your code to e.g. use the .. flip-flop operator.

    By the way, I strongly suspect that your regexp doesn't mean what you think it means. In particular, [^\^]+ matches a string of one or more characters that doesn't contain a caret (^). Since your input doesn't seem likely to contain any carets, this seems essentially equivalent to (?s:.+) (or just .+ if you use the /s modifier).

提交回复
热议问题