awk: print last few elements of a line

Written by - 0 comments

Published on - Listed in Linux Coding Shell


Had to find a way to print the last few elements of a line. I decided to go with awk but couldn't a correct solution for what I looked for.
With a combination of a stackoverflow question and try'n'err, I got myself the following working solution:

awk -F. '{print $(NF-5)"."$(NF-4)"."$(NF-3)"."$(NF-2)"."$(NF-1)"."$NF}'

In this example, the delimiter is a dot and awk prints the last 6 elements ($NF is always the last element itself).

Helpful in my case to find the last elements of a SNMP OID:

snmpwalk -v 2c -c monitoring -OanU target 1.3.6.1.4.1.7779.3.1.1.3.1.1.1.1 | egrep \"example.com\"$
.1.3.6.1.4.1.7779.3.1.1.3.1.1.1.1.10.110.122.122.46.99.104 = STRING: "example.com"

snmpwalk -v 2c -c monitoring -OanU target 1.3.6.1.4.1.7779.3.1.1.3.1.1.1.1 | egrep \"example.com\"$ | awk '{print $1}' | awk -F. '{print $(NF-5)"."$(NF-4)"."$(NF-3)"."$(NF-2)"."$(NF-1)"."$NF}'
110.122.122.46.99.104

Can also be helpful to find the last two octets of an ip address for example:

echo "192.168.50.110" | awk -F. '{print $(NF-1)"."$NF}'
50.110



Add a comment

Show form to leave a comment

Comments (newest first)

No comments yet.