You've probably come across awk command and its most simple use: splitting string elements separated by blank spaces. In this short post I'd like to expand a little bit on using awk field separators.
To demonstrate, let's inspect the output of ifconfig command on my Macbook:
[email protected]:/ $ ifconfig en0 en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500 ether dc:a9:04:7b:3f:44 inet6 fe80::879:43c0:48e2:124b%en0 prefixlen 64 secured scopeid 0xa inet 192.168.1.221 netmask 0xffffff00 broadcast 192.168.1.255 nd6 options=201<PERFORMNUD,DAD> media: autoselect status: active
I'd like to extract the IP address for this interface, which means we should first use grep to isolate just the line of output we want:
[email protected]:/ $ ifconfig en0 | grep "inet " inet 192.168.1.221 netmask 0xffffff00 broadcast 192.168.1.255
Great! Now it should be fairly easy to use awk to get that IP address. Since it's the second word from the left, we're telling awk to print parameter 2, {print $2}:
[email protected]:/ $ ifconfig en0 | grep "inet " | awk '{print $2}' 192.168.1.221
awk uses space as field separator by default, but you can also specify any other character to use as separator instead.
To continue with our example, I further parse the output (which is just the IP address at this stage) using . character as field separator:
[email protected]:/ $ ifconfig en0 | grep "inet " | awk '{print $2}' | awk -F. '{print $4}' 221
Obviously, if I want to access the last 2 octets of the IP address, I will modify the last awk command accordingly:
[email protected]:/ $ ifconfig en0 | grep "inet " | awk '{print $2}' | awk -F. '{print $3,$4}' 1 221
Leave a Reply