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

前端 未结 9 1197
离开以前
离开以前 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:32

    This might work for you (GNU sed):

    sed '/^abc$/,/^mno$/{//!b};d' file
    

    Delete all lines except for those between lines starting abc and mno

    0 讨论(0)
  • 2020-11-22 05:35

    Using sed:

    sed -n -e '/^abc$/,/^mno$/{ /^abc$/d; /^mno$/d; p; }'
    

    The -n option means do not print by default.

    The pattern looks for lines containing just abc to just mno, and then executes the actions in the { ... }. The first action deletes the abc line; the second the mno line; and the p prints the remaining lines. You can relax the regexes as required. Any lines outside the range of abc..mno are simply not printed.

    0 讨论(0)
  • 2020-11-22 05:36

    Don_crissti's answer from Show only text between 2 matching pattern?

    firstmatch="abc"
    secondmatch="cdf"
    sed "/$firstmatch/,/$secondmatch/!d;//d" infile
    

    which is much more efficient than AWK's application, see here.

    0 讨论(0)
提交回复
热议问题