awk field separator

Separating fields in awk Separating fields in awk

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
ether dc:a9:04:7b:3f:44
inet6 fe80::879:43c0:48e2:124b%en0 prefixlen 64 secured scopeid 0xa
inet netmask 0xffffff00 broadcast
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 netmask 0xffffff00 broadcast

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}'

** 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}'

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

See Also

Keep Learning with Me

Follow me on Facebook and Twitter or jump into Telegram chat!:
Recommended Software
I use Brave browser, it's awesome: Brave Browser I'm also a fan of SetApp for macOS: SetApp for macOS
IT Consultancy
I'm a principal consultant with Tech Stack Solutions. I help with cloud architectrure, AWS deployments and automated management of Unix/Linux infrastructure. Get in touch!

Recent Tweets