I came across a good example today. Say we want to show the current local ip address. There are other ways to do this, but one way is by parsing the output of "ifconfig <interface>" -- here are the first four lines:
Code: Select all
$ ifconfig eth0
eth0 Link encap:Ethernet HWaddr 00:0f:fe:7f:1c:5d
inet addr:192.168.0.163 Bcast:192.168.0.255 Mask:255.255.255.0
inet6 addr: fd00::20f:feff:fe7f:1c5d/64 Scope:Global
inet6 addr: fe80::20f:feff:fe7f:1c5d/64 Scope:Link
Code: Select all
$ ifconfig eth0 | grep "inet addr" | awk -F: '{print $2}' | awk '{print $1}' | head -1
192.168.0.163
Code: Select all
$ ifconfig eth0 | awk '/inet addr/ {print}'
inet addr:192.168.0.163 Bcast:192.168.0.255 Mask:255.255.255.0
Code: Select all
$ ifconfig eth0 | awk -F: '/inet addr/ {print $2}'
192.168.0.163 Bcast
Code: Select all
$ ifconfig eth0 | awk -F: '/inet addr/ {gsub (/ Bcast/, ""); print $2}'
192.168.0.163
One more thing -- the very first thing you should ask yourself when you have a problem like this is "Is there another core command that will give me information that is closer to what I need, and therefore easier to parse?" In this example, we started with "ifconfig" -- what if we instead start with "ip addr"?
Code: Select all
$ ip addr show eth0
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 00:0f:fe:7f:1c:5d brd ff:ff:ff:ff:ff:ff
inet 192.168.0.163/24 brd 192.168.0.255 scope global eth0
valid_lft forever preferred_lft forever
If you have something you're working on in awk and want help with, or something you did or found that seems particularly interesting, please post it here!