user2831586
user2831586

Reputation: 119

awk checking for multiple patterns in file

Here's my code:

/usr/bin/gawk '{
!/simsX.ip-17-31-28-19/ { a[".*Unauthorized.*Dup.*"] += gsub("(| ).*Unauthorized.*Duplication.*( |)", "&") }
!/simsX.ip/ { a[".*En_NoConn-.*"] += gsub("(| ).*En_NoConn-.*( |)", "&") }        
} END {
for (i in a)
printf("%s=%s\n", i, a[i])
}' /home/nagios/graphite-web_access.log

When I run the above code I get the following error:

gawk: cmd. line:2:                                                                      !/simsX.ip-17-31-28-19/ { a[".*Unauthorized.*Dup.*"] += gsub("(| ).*Unauthorized.*Duplication.*( |)", "&") }
gawk: cmd. line:2:                                                                                              ^ syntax error
gawk: cmd. line:3: !/simsX.ip/ { a[".*En_NoConn-.*"] += gsub("(| ).*En_NoConn-.*( |)", "&") }   
gawk: cmd. line:3:             ^ syntax error

This code is suppose to search a file for the specified strings and then output results in the following format:

.*Unauthorized.*Dup.*=48
.*En_Conn-.*=0

I'm having issues identifying where the problem lies or how to fix it. Please advise.

Upvotes: 1

Views: 47

Answers (1)

Ed Morton
Ed Morton

Reputation: 203254

You put a standalone condition inside an action part of the script instead of a condition part of the script.

Good:

awk '<condition> { <action> }'

Bad:

awk '{ <condition> { <action> } }`

You wrote:

awk '{   # <<<< NOTE!!!!
    !/simsX.ip-17-31-28-19/ { a[".*Unauthorized.*Dup.*"] += gsub("(| ).*Unauthorized.*Duplication.*( |)", "&") }
    !/simsX.ip/ { a[".*En_NoConn-.*"] += gsub("(| ).*En_NoConn-.*( |)", "&")
}    # <<<< NOTE!!!
'

so your conditions (!/simsX.ip-17-31-28-19/ and !/simsX.ip/) are inside an action block ({...}). You probably meant to write:

awk '
    !/simsX.ip-17-31-28-19/ { a[".*Unauthorized.*Dup.*"] += gsub("(| ).*Unauthorized.*Duplication.*( |)", "&") }
    !/simsX.ip/ { a[".*En_NoConn-.*"] += gsub("(| ).*En_NoConn-.*( |)", "&") }        
'    

or less likely:

awk '{
    if (!/simsX.ip-17-31-28-19/) { a[".*Unauthorized.*Dup.*"] += gsub("(| ).*Unauthorized.*Duplication.*( |)", "&") }
    if (!/simsX.ip/) { a[".*En_NoConn-.*"] += gsub("(| ).*En_NoConn-.*( |)", "&")
}
'

Upvotes: 3

Related Questions