I am trying to awk information from a named file based on the first three octets of an IP. In this file the IP can be in either column 2 or column 4. If the IP is in column 2 I'd like to print what is in column 2 then what it is column 1. If the IP is in column 4 I'd like to print column 4 and column 1. (Column 1 in the server name).

This is an example of the output with all the columns printed:

awk /10.1.49/ /var/named/internal/Domain/abc.com

The output looks like this:

server01      IN      A  
server02      IN      A  

I want to sort by the IP column and then print IP and server name:  server01  globalname01.abc.com  globalname02.abc.com  server02  

I do know how to use {print NF} to get a column count, I just don't know how to use that information, such as if NF returns 4 then {print $4 $1} but if NF returns 2 then {print $2 $1} ... and preferably sorted on top of that (but I can throw that data out to a file and then read it back in again to sort it if I need to).

2 Answers 2



$ awk '$NF~/^10\.1\.49/ {sub(/;/, "", $1); print $NF,$1}' file | sort server01 globalname01.abc.com globalname02.abc.com server02

How it works

  • $NF~/^10\.1\.49/ {..}

    This selects lines for which the last column begins with10.1.49. For these lines the command in braces are executed.

  • sub(/;/, "", $1)

    The first of the commands in braces is a substitute command. It removes the ; from the first field if one is present.

  • print $NF,$1

    This prints the last field followed by the (possibly modified) first field.

  • sort

    This sorts the output. Note that there are possible ways of sorting IP addresses and sort's many options may help you get the output that you want.

awk '{ if ($1 ~ /;.*/) { print $2, substr($1, 2); } else { print $4, $1; } }' file  | sort

Output: server01 globalname01.abc.com globalname02.abc.com server02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .