bashfileparsing

BASH - read lines from section of file


I have a file formatted like this:

[SITE1]
north
west

[MOTOR]
west
south
north

[AREA]
west
east
north

[CLEAR]

What I need to be able to do is read all values from a specific section.

Eg: read AREA and be returned:

west
east
north

The examples I've found online are for ini files, which have key value pairs. Can anyone help advise how I can do this ?

Thanks


Solution

  • Using sed :

    category=MOTOR; sed -nE "/^\[$category\]$/{:l n;/^(\[.*\])?$/q;p;bl}" /path/to/your/file
    

    It doesn't do anything until it matches a line that consists of your target category, at which point it enters a loop. In this loop, it consumes a line, exits if it's an empty line or another category (or the end of the file) and otherwise prints the line.

    The sed commands used are the following :

    You can try it here.