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

后端 未结 8 2262
生来不讨喜
生来不讨喜 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:54

    You can do what you want with sed by suppressing the normal printing of pattern space with -n. For instance to include the patterns in the result you can do:

    $ sed -n '/PAT1/,/PAT2/p' filename
    PAT1
    3    - first block
    4
    PAT2
    PAT1
    7    - second block
    PAT2
    PAT1
    10    - third block
    

    To exclude the patterns and just print what is between them:

    $ sed -n '/PAT1/,/PAT2/{/PAT1/{n};/PAT2/{d};p}' filename
    3    - first block
    4
    7    - second block
    10    - third block
    

    Which breaks down as

    • sed -n '/PAT1/,/PAT2/ - locate the range between PAT1 and PAT2 and suppress printing;

    • /PAT1/{n}; - if it matches PAT1 move to n (next) line;

    • /PAT2/{d}; - if it matches PAT2 delete line;

    • p - print all lines that fell within /PAT1/,/PAT2/ and were not skipped or deleted.

提交回复
热议问题