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

后端 未结 8 2568
生来不讨喜
生来不讨喜 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 05:49

    What about the classic sed solution?

    Print lines between PAT1 and PAT2 - include PAT1 and PAT2

    sed -n '/PAT1/,/PAT2/p' FILE
    

    Print lines between PAT1 and PAT2 - exclude PAT1 and PAT2

    GNU sed
    sed -n '/PAT1/,/PAT2/{/PAT1/!{/PAT2/!p}}' FILE
    
    Any sed1
    sed -n '/PAT1/,/PAT2/{/PAT1/!{/PAT2/!p;};}' FILE
    

    or even (Thanks Sundeep):

    GNU sed
    sed -n '/PAT1/,/PAT2/{//!p}' FILE
    
    Any sed
    sed -n '/PAT1/,/PAT2/{//!p;}' FILE
    

    Print lines between PAT1 and PAT2 - include PAT1 but not PAT2

    The following includes just the range start:

    GNU sed
    sed -n '/PAT1/,/PAT2/{/PAT2/!p}' FILE
    
    Any sed
    sed -n '/PAT1/,/PAT2/{/PAT2/!p;}' FILE
    

    Print lines between PAT1 and PAT2 - include PAT2 but not PAT1

    The following includes just the range end:

    GNU sed
    sed -n '/PAT1/,/PAT2/{/PAT1/!p}' FILE
    
    Any sed
    sed -n '/PAT1/,/PAT2/{/PAT1/!p;}' FILE
    

    1 Note about BSD/Mac OS X sed

    A command like this here:

    sed -n '/PAT1/,/PAT2/{/PAT1/!{/PAT2/!p}}' FILE
    

    Would emit an error:

    ▶ sed -n '/PAT1/,/PAT2/{/PAT1/!{/PAT2/!p}}' FILE
    sed: 1: "/PAT1/,/PAT2/{/PAT1/!{/ ...": extra characters at the end of p command
    

    For this reason this answer has been edited to include BSD and GNU versions of the one-liners.

提交回复
热议问题