LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   parsing text using sed/awk or similar??? (https://www.linuxquestions.org/questions/programming-9/parsing-text-using-sed-awk-or-similar-657675/)

freeindy 07-23-2008 08:04 AM

parsing text using sed/awk or similar???
 
Hi,

I have a text file (conf) like:

Code:

Section AAA
        var1 = abba
        var2 = baab
        var3 = abab
EndSection

Section BBB
        var1 = nisse
        var2 = lasse
        var3 = salle
EndSection

I want to get out sections individually into a variable (bash) but I can't get my head around sed how to do it. Then eventually get each variable correctly. Any ideas?

Thanks,
Indy

Kenhelm 07-23-2008 11:27 AM

Each section of variables could be put into an array:-
Code:

#!/bin/bash
AAA=("" $(sed -n '/Section AAA/, /EndSection/ s/.* = \(.*\)/ \1/p' filename))
echo ${AAA[1]} ${AAA[2]} ${AAA[3]}

abba baab abab

Or all the variables could be put into one array:-
Code:

#!/bin/bash
all=("" $(sed -n 's/.* = \(.*\)/ \1/p' filename))
echo ${all[1]} ${all[2]} ${all[3]}
echo ${all[4]} ${all[5]} ${all[6]}

abba baab abab
nisse lasse salle


pixellany 07-23-2008 11:46 AM

I read it as wanting each SECTION in a variable.

Section = `sed -n '/AAA/,/EndSection/p' filename`

I just realized that, unlike many regexes, the "range" construct in SED is not greedy--ie, it stops on the first instance of "EndSection"

theNbomr 07-23-2008 05:51 PM

In perl (awk, too, but there are others in this forum who do better awk than do I), this is a one-liner:
Code:

perl -e '$/="\n\n"; @sections=<>; foreach $section (@sections){ print "\nSECTION = $section\n";
--- rod.

ghostdog74 07-23-2008 08:06 PM

Code:

set -- $(awk -F"=" '/Section/{f=1;next}/EndSection/{f=0}f{print $2}' file)
echo $1
echo $2


freeindy 07-24-2008 04:04 AM

thanks lads,

Works beautifully

Indy


All times are GMT -5. The time now is 04:53 PM.