How to print lines between two patterns, inclusive or exclusive (in sed, AWK or Perl)?

后端 未结 8 2264
生来不讨喜
生来不讨喜 2020-11-21 05:37

I have a file like the following and I would like to print the lines between two given patterns PAT1 and PAT2.



        
8条回答
  •  甜味超标
    2020-11-21 06:00

    For completeness, here is a Perl solution:

    Print lines between PAT1 and PAT2 - include PAT1 and PAT2

    perl -ne '/PAT1/../PAT2/ and print' FILE
    

    or:

    perl -ne 'print if /PAT1/../PAT2/' FILE
    

    Print lines between PAT1 and PAT2 - exclude PAT1 and PAT2

    perl -ne '/PAT1/../PAT2/ and !/PAT1/ and !/PAT2/ and print' FILE
    

    or:

    perl -ne 'if (/PAT1/../PAT2/) {print unless /PAT1/ or /PAT2/}' FILE 
    

    Print lines between PAT1 and PAT2 - exclude PAT1 only

    perl -ne '/PAT1/../PAT2/ and !/PAT1/ and print' FILE
    

    Print lines between PAT1 and PAT2 - exclude PAT2 only

    perl -ne '/PAT1/../PAT2/ and !/PAT2/ and print' FILE
    

    See also:

    • Range operator section in perldoc perlop for more on the /PAT1/../PAT2/ grammar:

    Range operator

    ...In scalar context, ".." returns a boolean value. The operator is bistable, like a flip-flop, and emulates the line-range (comma) operator of sed, awk, and various editors.

    • For the -n option, see perldoc perlrun, which makes Perl behave like sed -n.

    • Perl Cookbook, 6.8 for a detailed discussion of extracting a range of lines.

提交回复
热议问题