In Linux/Unix systems, we have one command named as awk/nawk which most of time used to print some specific columns and can do some other operations with it. But what if we need to work on only certain part of it, but not complete column. For this we have one method in awk command which is called substr. Let’s take some examples to understand How Awk Substr Works.

Awk has many such important built-in function and variable which could be very useful while working with AWK

Select Substr from Beginning

If we need to print IP address of particular interface card, like below we tried to print for wlp2s0 (Wireless) lan card in Ubuntu Machine.

▶ ip a show dev wlp2s0| awk '/inet /{print $2}'

So we tried to print second column that contain “inet ” word. But what if we don’t like print Net-mask with same, for same we can use substr like below.

▶ ip a show dev wlp2s0| awk '/inet /{print substr($2,1,13)}'

So now we print second column from first character to thirteenth character only, one thing need to notice here index start from 1 instead of 0 like any other computer counts.

Select Substr from End

But what if IP address have more than thirteen characters, here there is way to start counting through reverse order as well.

▶ ip a show dev wlp2s0| awk '/inet /{print substr($2,1,length($2)-3)}'

So in above we calculate length of column 2 and then subtract three character from it, this makes it bit more promising, this could also have some issues in case we used single or triple character Net-Mask. For same we have split function in AWK.