Paul Dawson
Paul Dawson

Reputation: 1382

awk: run time error: negative field index $-1

I'm trying to print the first column and (when existing) the second last column, but sometimes the lines being processed only have one column.

Example:

host1, auth ldap system-auth { bind-dn CN=xx-w-xx,OU=iResources,DC=int,DC=dir,DC=dimsum,DC=com bind-pw xxxxx login-attribute samaccountname search-base-dn ou=wbab,dc=int,dc=dir,dc=dodo,dc=com servers { 10.10.10.1 } }
host2

I've tried:

`awk '{print $1, $(NF-2) ? $(NF-2) : "None" }'`

I am getting an error when processing the second line:

host1, 10.10.10.1
awk: run time error: negative field index $-1

How do we deal with a negative or non-existent field?

Upvotes: 2

Views: 1175

Answers (2)

Jotne
Jotne

Reputation: 41460

You were close. This should do it:

awk '{print $1,(NF>2?$(NF-2):"None")}' file
host1, 10.10.10.1
host2 None

It tests if the number of fields is greater than two. You did check if there was data in last field -2, and if that does not exist, it fails. Furthermore, you should also use parentheses around your ternary operator (expr1 ? expr2 : expr3).

Upvotes: 5

hek2mgl
hek2mgl

Reputation: 158090

You may just want to keep it simple first. A readable and understandable implementation would be this:

awk '{if(NF==1){print $1} else { print $1, $(NF-2)}}' file

But don't get me wrong, I'm not saying that shorter versions shouldn't be used. I would use Jotne's solution. But sometimes it's just good to start with a simple, explicit implementation and then reduce it from there.

Upvotes: 2

Related Questions