trying to cope with awk difficulties

The data we are searching is populated in this way:

----IP---------DAY----MONTH----DATE--------TIME---------YEAR
12.3234.34-----Fri------Nov-------15-------18:05:14 GMT---2008

I want the user to be able to search for the data according to month and year.
However, I cannot quite figure out how to do this. Above is the code i have and i can't understand what is wrong?

If we try and put in the variable e.g Nov, it wont give us any results.

It works only if instead of "$MONTH" we enter the month itself e.g Nov or Sep.

You need to add single quotes to pass inside awk the shell variable:

awk '$3=='"$MONTH"' {print $1, $2, $3, $4, $5, $6}' *.hits

I have tried this and it did not work. I also tried:

and this also didnt work.

I'm a bit stumped.

You need to specify the delimiter used by your flat file in the awk statement..

May not be the case...ignore this

You need to use AWK's special way of passing variables into it:

echo "Enter month: "

read MONTH

awk -v mon="$MONTH"  '$3~mon { print $1, $2, $3, $4, $5, $6}' *.hits 

Or equally:

awk '$3~mon { print $1, $2, $3, $4, $5, $6}'  mon="$MONTH" *.hits

Same thing if year is also needed:

awk -v mon="$MONTH" -v year="$YEAR" '$3~mon && $6~year { print ... } *.hits

thanks very much.

can you use AWK to search for unique IP's within this?

so if the same IP logged on more than once it would list the one IP with all the hits?

I already have the IP's in a populated file with the month and date.

Simply modify the given code:

echo "Enter month: "

read MONTH

echo "Enter ip: "

read IP


awk -v mon="$MONTH" -v ip="$IP" '$3~mon && $1~ip { print ... }' *.hits

Admitted that rubin's way is much more clearer and readable, you can pass variables also interrupting and resuming the awk code by the means of single quotes, like I posted before.

The problem is that before I made a mistake, you also need to add a couple of double quotes to complicate things a little bit more :smiley:

awk '$3=="'"$MONTH"'" {print $1, $2, $3, $4, $5, $6}' *.hits

Here goes another unconventional way of passing variables to awk:

echo "Enter month: "

read MONTH

awk '/'$MONTH'/ { print ... }' file

Caveat emptor:
The above approach does not work if the variable has whitespaces, newlines or certain special characters ( |, /, ...) in it.
So it's always recommended using the conventional way -v var=... .