1

I want to parse each line from a text with this structure:

  ipv4address: 1.2.3.4/29
  ipv4gateway: 1.2.3.1
  ipv4mtu: 1500
  ipv4dnsserver: 8.8.8.8
  ipv4dnsserver: 8.8.4.4

Newlines are seperated by \n.

To generate this file I use a program which will output some information:

CONFIG=$(umbim $DBG -d $device -n -t $tid config) || {
        echo "mbim[$$]" "config failed"
        return 1
    }

then I write out the $CONFIG variable to a file, just to reread it again, which seems wrong to me.

echo "$CONFIG" > /tmp/ip

Then after that I use grep to get the information:

IP=$(grep "ipv4address" /tmp/ip |grep -E -o "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)")
NM=$(grep "ipv4address" /tmp/ip |grep -o '.\{2\}$')
GW=$(grep "ipv4gateway" /tmp/ip |grep -E -o "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)")

I want to avoid writing to a file. It would be better, or at least it seems better if I could grep on the $CONFIG variable. But using echo $CONFIG will not yield the results as newlines are ommitted with this. The same with printf.

I am using busybox if that helps.

BusyBox v1.25.1 () built-in shell (ash)

Edit: This is what happens when I want to print out the variable with echo:

$ CONFIG=$(cat /tmp/ip)
$ echo -e $CONFIG
ipv4address: 1.2.3.4/29 ipv4gateway: 1.2.3.1 ipv4mtu: 1500 ipv4dnsserver: 8.8.8.8 ipv4dnsserver: 8.8.4.4
fsp
  • 515
  • 6
  • 21
  • `echo -e` will also output new lines. – erik258 Jan 02 '17 at 23:05
  • Thanks, I added an example some seconds ago. Unsuccessfull unfortunateley. – fsp Jan 02 '17 at 23:05
  • 3
    Without dealing with `grep | grep`, you can use: `IP=$(echo "$CONFIG" | grep "ipv4address" | grep -E …)` etc. Note the double quotes around `"$CONFIG"`. You may not be able to use Bash 'here strings' since you're using BusyBox, but they would save a process if available. I'd look at using `sed` rather than `grep | grep`. Note [Capturing multi-line output to a bash variable](https://stackoverflow.com/questions/613572/). – Jonathan Leffler Jan 02 '17 at 23:09
  • A quick and dirty `sed` could be added (eg. `echo -e "$CONFIG" | sed $'s/ ip/\\\nip/g'`) – l'L'l Jan 02 '17 at 23:18
  • to the downvoter: why the downvote? – fsp Jan 03 '17 at 04:14

2 Answers2

2

Shell variable should almost always be quoted. If instead of echo $CONFIG | grep ... you use echo "$CONFIG" | grep ..., the newlines will be preserved and you'll get the expected result.

xhienne
  • 5,738
  • 1
  • 15
  • 34
0

Why won't you just use something like this?

eval $(umbim $DBG -d $device -n -t $tid config | tr -d ' ' | grep ^ipv4 | tr a-z: A-Z=)
IP=${IPV4ADDRESS%/*}
NM=${IPV4ADDRESS##*/}
GW=$IPV4GATEWAY
Alex P.
  • 30,437
  • 17
  • 118
  • 169