AWKing or GREPing brackets [ ]?

Viewed 74

I've searched all over and couldn't find a solution.

How would I awk or grep the following:

$ mbimcli -d /dev/cdc-wdm0 -p --query-ip-configuration
[/dev/cdc-wdm0] IPv4 configuration available: 'address, gateway, dns'
 IP [0]: '11.22.333.44/55'
Gateway: '14.13.198.4'
DNS [0]: '172.17.1.101'
DNS [1]: '172.17.1.102'
DNS [2]: '172.17.1.101'
DNS [3]: '172.17.1.102'

So that I end up with:

11.22.33.44/55

I've tried a bunch of different combinations with both grep and awk and couldn't find a solution.

4 Answers

You can do this in a single awk:

mbimcli -d /dev/cdc-wdm0 -p --query-ip-configuration |
awk '$1 == "IP" {gsub(/\047/, "", $NF); print $NF}'

11.22.333.44/55

Using cat file as I don't have mbimcli -d /dev/cdc-wdm0 -p --query-ip-configuration:

$ cat file | awk -F"'" '/IP \[/{print $2}'
11.22.333.44/55

$ cat file | awk -F"'" '/Gateway/{print $2}'
14.13.198.4

or maybe this is all you need if the output of that command always looks like the example you posted:

$ cat file | awk -v RS= -F"'" '{print $5}'
11.22.333.44/55

$ cat file | awk -v RS= -F"'" '{print $8}'
14.13.198.4

something like this:

grep '[0-9]' file_with_text | awk '{print $NF}

grep [0-9] only lines with numbers and pipe the output into awk. The $NF will return the last element. If you want only the line that has the /, just add it to grep [0-9]/.

Also, for a complete answer, you can pipe the output of the command into grep:

mbimcli -d /dev/cdc-wdm0 -p --query-ip-configuration | grep '[0-9]/' | awk '{print $NF}

I would harness tr for preprocessing and GNU AWK for processing, let file.txt content be

 IP [0]: '11.22.333.44/55'
Gateway: '14.13.198.4'
DNS [0]: '172.17.1.101'
DNS [1]: '172.17.1.102'
DNS [2]: '172.17.1.101'
DNS [3]: '172.17.1.102'

then

cat file.txt | tr -d "'" | awk '/IP/{print $NF}'

output

11.22.333.44/55

Explanation: use tr to delete ' then awk to print last column ($NF) if row contain IP.

(tested in tr (GNU coreutils) 8.30 and GNU Awk 5.0.1)

Related