Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I skip an empty record in my awk script? 1

Status
Not open for further replies.

johngiggs

Technical User
Oct 30, 2002
492
US
I have an input file that's missing some data. I need to figure out how to only print the server name if there is no nameserver data.

server1.mydomain.com
search somdomain.com
nameserver 10.1.1.154
nameserver 10.1.1.155

server2.mydomain.com

server3.mydomain.com

server4.mydomain.com
; generated by /sbin/dhclient-script
search mydomain.com
nameserver 10.1.1.155
nameserver 10.1.1.154

My awk script so far looks like this:

/\.com/ && $0 !~ /search /{server = $1; getline; if ($0 !~ /[a-z]/) nameserver = ""}
/^nameserver/{if (NF) nameserver[++nrc] = $2}
/^$/{for (i=1;i<=nrc;i++) printf ("%-40s %-18s\n", server, nameserver)}

My desired output is:

server1.mydomain.com 10.1.1.154 10.1.1.155
server2.mydomain.com
server3.mydomain.com
server4.mydomain.com 10.1.1.154 10.1.1.155

There will be times when there are more than 2 different nameservers.

Any help would be greatly appreciated.

Thanks,

John
 
Try this:

Code:
[green]/\.com/[/green] && [blue]$0[/blue] !~ [green]/search /[/green]{server = [blue]$1[/blue]}
[green]/^nameserver/[/green]{[olive]if[/olive] ([blue]NF[/blue]>1) nameserver[++nrc] = [blue]$2[/blue]}
[green]/^$/[/green]{[b]printf[/b] ([red]"[/red][purple]%-40s [/purple][red]"[/red], server); [olive]for[/olive] (i=1;i<=nrc;i++) [b]printf[/b] ([red]"[/red][purple]%-18s [/purple][red]"[/red], nameserver[i]); [b]printf[/b] [red]"[/red][purple]\n[/purple][red]"[/red]; nrc=0}

There's no need to delete the contents of the array, however you do need to reset the array index for each server, hence the nrc=0. If you do need to empty the array for some reason, better to use for (n in nameserver) delete n for portability. My awk complains "awk: Cannot make an assignment to nameserver. It is an array name.".

I'm assuming there is a blank line at the end of the input data, otherwise you will need to handle the printing of the final server in an END { } clause.

if (NF) was redundant; NF will always be true if /^nameserver has matched; however it's worthwhile checking whether it is >1 (i.e. $2 is defined).

Annihilannic
[small]tgmlify - code syntax highlighting for your tek-tips posts[/small]
 
Thanks Annihilannic! That worked great.

I had forgotten about setting the variable to 0. It makes sense now!

Thanks again.

John
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top