Link to home
Start Free TrialLog in
Avatar of Frosty555
Frosty555Flag for Canada

asked on

A little bit of sed/awk magic

Hi guys,

I'm looking for an expert who is familiar with sed and awk, I need to parse a text file using Bash. My text file looks something like this:

; this is a comment

[mapping]

; some more comments here
foo=bar
apple    =   banana

; and more comments
       qwerty=dvorak

[statement]
this is a block of text which should
be read verbatim, without any
; parsing of any kind = that was applied
to the = mapping section 

above.

Open in new window


Basically what I need to do is:

1) In the "[mapping]" section of the file:
    a) Ignore lines that are pure whitespace or that start with a semicolon
    b) Get each mapping pair, e.g. "foo" and "bar", "apple" and "banana" etc
    c) Trim whitespace off the pairs

2) In the "[statement]" section of the file
    a) Get the entire block of text following the line that says [statement], verbatim, without any of the parsing or formatting that was done in the [mapping] section.

I hope this isn't too complicated. It doesn't need to be really robust, the example I gave above is about as bad as the text file will get and it can die horribly if it is malformed. I'm not concerned much with efficiency either (the file I'm parsing is always going to be pretty small), so whatever solution can read the file in over and over again, re-parse things more than it needs to etc.
ASKER CERTIFIED SOLUTION
Avatar of woolmilkporc
woolmilkporc
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
A2.
awk 'BEGIN{found=0;} /\[statement\]/ {found=1;} {if(found==1) print}'  /path-to-inputfile | tail -n+2
Here is another version of A2 by perl command line

perl -ne 'if (/\[statement\]/){$state=1; next;} print if ($state eq 1);'  /path-to-inputfile
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Frosty555

ASKER

woolmilkporc:
awk '/\[mapping\]/,/\[statement\]/ {if($0~"=") print $1 $2 $3}' inputfile

Open in new window

This successfully parses out the contents of the [mapping] section.

For your question, the [statement] block ends at the end of the file.

wesly_chen:
awk 'BEGIN{found=0;} /\[statement\]/ {found=1;next} {if(found==1) print}'  /path-to-inputfile

Open in new window

This successfully grabs the [statement] block.

Thanks guys!