Shell: use grep on a variable with newlines

757 views Asked by At

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
2

There are 2 answers

0
xhienne On BEST ANSWER

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.

0
Alex P. On

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