How do I extract lines between two line delimiters in Perl?

前端 未结 6 1692
醉酒成梦
醉酒成梦 2020-12-09 06:23

I have an ASCII log file with some content I would like to extract. I\'ve never taken time to learn Perl properly, but I figure this is a good tool for this task.

Th

6条回答
  •  [愿得一人]
    2020-12-09 06:29

    From perlfaq6's answer to How can I pull out lines between two patterns that are themselves on different lines?


    You can use Perl's somewhat exotic .. operator (documented in perlop):

    perl -ne 'print if /START/ .. /END/' file1 file2 ...
    

    If you wanted text and not lines, you would use

    perl -0777 -ne 'print "$1\n" while /START(.*?)END/gs' file1 file2 ...
    

    But if you want nested occurrences of START through END, you'll run up against the problem described in the question in this section on matching balanced text.

    Here's another example of using ..:

    while (<>) {
        $in_header =   1  .. /^$/;
        $in_body   = /^$/ .. eof;
    # now choose between them
    } continue {
        $. = 0 if eof;  # fix $.
    }
    

提交回复
热议问题