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

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

    This is like a foot-note to the 2 top answers above (awk & sed). I needed to run it on a large number of files, and hence performance was important. I put the 2 answers to a load-test of 10000 times:

    sedTester.sh

    for i in `seq 10000`;do sed -n '/PAT1/,/PAT2/{/PAT1/!{/PAT2/!p;};}' patternTester >> sedTesterOutput; done
    

    awkTester.sh

     for i in `seq 10000`;do awk '/PAT1/{flag=1; next} /PAT2/{flag=0} flag' patternTester >> awkTesterOutput; done
    

    Here are the results:

    zsh sedTester.sh  11.89s user 39.63s system 81% cpu 1:02.96 total
    zsh awkTester.sh  38.73s user 60.64s system 79% cpu 2:04.83 total
    

    sed solutions seems to be twice as fast as the awk solution (Mac OS).

提交回复
热议问题