awk ignore case isn't working

1.1k views Asked by At

I am using this code to get ip entries from host file with ignore case and it doesn't seem to work on AIX

Input file

172.23.1.230    enboprtpapzp04.digjam.com  enboprtpapzp04
#172.23.0.33    enboprtpapzp04.digjam.com  enboprt        enboprtpapzp04
172.23.1.230    enboprtpapzp04.fixture.com  enboprtpap    enboprtpapzp04

awk -v client="$client" 'BEGIN {IGNORECASE = 1}{k=0; for (i=1;i<=NF;i++){if ($i==client){print $1}; k++}}' file

See the output below

client=ENBOPRTPAPZP04
awk -v client="$client" 'BEGIN {IGNORECASE = 1}{k=0; for (i=1;i<=NF;i++){if ($i==client){print $1}; k++}}' file

Nothing comes up

expected output

    grep -i ENBOPRTPAPZP04 /etc/hosts | awk '{print $1}' | grep -v "^#"
172.23.1.230
172.23.1.230
1

There are 1 answers

11
James Brown On BEST ANSWER

It works here:

$ awk -v client="$client" 'BEGIN{IGNORECASE = 1} $2==client && /^[^#]/{print $1}' your_hosts
172.23.1.230
172.23.1.230

Are you sure you are using GNU awk? If not, you could:

$ awk -v client="$client" 'tolower($2)==tolower(client) && /^[^#]/{print $1}' your_hosts

In the light of the resent - whoops, I meant recent - edits to the question and the mentioning of the loop in the comments I'll add this:

$ awk -v client="$client" '{for(i=1;i<=NF;i++) if(tolower($i)==tolower(client) && $1!~/^#/)print $1}' your_new_hosts
172.23.1.230
172.23.1.230

Also, check @EdMorton's last comment below for a non-looping version.

The check for the /^#/ could be outside of the action block in the condition part:

$ awk ... '!/^#/ {for(i=1;i<=NF;i++) if(tolower($i)==tolower(client)) print $1}' your_new_hosts