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
Shell variable should almost always be quoted. If instead of
echo $CONFIG | grep ...
you useecho "$CONFIG" | grep ...
, the newlines will be preserved and you'll get the expected result.