How to select lines between two marker patterns which may occur multiple times with awk/sed

前端 未结 9 1303
离开以前
离开以前 2020-11-22 04:41

Using awk or sed how can I select lines which are occurring between two different marker patterns? There may be multiple sections marked with these

9条回答
  •  一生所求
    2020-11-22 05:15

    I tried to use awk to print lines between two patterns while pattern2 also match pattern1. And the pattern1 line should also be printed.

    e.g. source

    package AAA
    aaa
    bbb
    ccc
    package BBB
    ffffd
    eee
    package CCC
    fff
    ggg
    hhh
    iii
    package DDD
    jjj
    

    should has an ouput of

    package BBB
    ffffd
    eee
    

    Where pattern1 is package BBB, pattern2 is package \w*. Note that CCC isn't a known value so can't be literally matched.

    In this case, neither @scai 's awk '/abc/{a=1}/mno/{print;a=0}a' file nor @fedorqui 's awk '/abc/{a=1} a; /mno/{a=0}' file works for me.

    Finally, I managed to solve it by awk '/package BBB/{flag=1;print;next}/package \w*/{flag=0}flag' file, haha

    A little more effort result in awk '/package BBB/{flag=1;print;next}flag;/package \w*/{flag=0}' file, to print pattern2 line also, that is,

    package BBB
    ffffd
    eee
    package CCC
    

提交回复
热议问题