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:

greys@maverick:/ $ 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:

greys@maverick:/ $ 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}:

greys@maverick:/ $ 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:

greys@maverick:/ $ 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:

greys@maverick:/ $ ifconfig en0 | grep "inet " | awk '{print $2}' | awk -F. '{print $3,$4}'
1 221

See Also

Contact Me

Follow me on Facebook, Twitter or Telegram:
I learn with Educative: Educative
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 Articles
24 Mar 2024

Homelab: Mac Pro 2013 32GB

30 Sep 2023

macOS Sonoma 14.0

26 Sep 2023

Video: What Browser Do You Use?

Recent Tweets