如何根据“开始”和“结束”模式提取文件的各个部分

时间:2014-01-11 20:59:58

标签: bash scripting debian

我尝试根据文本文件中出现(或有时重新出现)的某种模式提取文本文件的不同部分。到目前为止,我已经能够通过逐行读取文件然后点击这一行来做到这一点,但我感觉这不是最有效的方法。请参阅下面的模式示例:

policy-map type stackoverflow

    random lines of indented text

non-indented text (signifying the beginning of the next "section" in the file)

还有其他方法可以实现这个目标吗?我在想像awk或sed这样的东西可能会起作用,但是我对使用这些程序知道如何去做这件事并不够熟练。

2 个答案:

答案 0 :(得分:2)

使用

awk '/^starting/{l=1;print;next} /^\S/{l=0} l' file

starting是一个任意的起始字符串

答案 1 :(得分:0)

你也可以使用sed:

sed -rn '/^pattern/ { :again p; n; /^$|^\s+/ b again; }' file