Monday, October 25, 2021

[SOLVED] How can I extract sections of a file based on a "starting" and "ending" pattern

Issue

I am try to extract different sections of a text file based on a certain pattern that occurs (or reoccurs sometimes) in the text file. So far I have been able to do this by reading the file line by line and then grepping this line, but I have a feeling that this is not the most efficient way to go about doing this. Please see below for an example of the pattern:

policy-map type stackoverflow

    random lines of indented text

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

Is there any other way that I could go about accomplishing this? I was thinking that something like awk or sed might work, but I am not skilled enough in the use of these programs to know how to go about doing this.


Solution

With :

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

starting is an arbitrary starting string



Answered By - Gilles Quenot