Bash: How to read multiline options from olsrd config (nginx similar)

116 views Asked by At

How do you parse (and modify) following config: (extract from olsrd.conf)

Hna4
{
4.3.2.1 255.255.255.255
#   Internet gateway:
#   0.0.0.0      0.0.0.0
#   more entries can be added:
#   192.168.1.0  255.255.255.0
1.2.3.4 255.255.255.255
2.3.4.5 255.255.255.255
}

I would need this config (stored in a bash variable) in this format:

1.2.3.4 255.255.255.255;2.3.4.5 255.255.255.255

And also would need this to write back from this format to the olsrd.conf file.

(it's similar to nginx config, just that the brackets begin in next line.)

After some research i came up with using grep to find the linenumber of "Hna4" in olsrd.conf, then from this point on find the linenumber of the first closing bracket, then get all lines between those two linenumbers, then parse content..

Is there some other(better) way to achieve this?

1

There are 1 answers

1
SLePort On

With sed :

$ ips=$(sed -n '/Hna4/,/}/ { /^ *\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}/ { N ;/^ *\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}/ s/\n/;/ p } } ' < sourcefile)
$ echo $ips
1.2.3.4 255.255.255.255;2.3.4.5 255.255.255.255

Update :

To output all ip :

$ ips=$(sed -n '/Hna4/,/}/ { /}/! { /^ *\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}/ { H } };/}/ { x; s/\n/;/g; s/^;//; s/\n}//; p }}' file)
$ echo $ips
4.3.2.1 255.255.255.255;1.2.3.4 255.255.255.255;2.3.4.5 255.255.255.255