1834814 Members
2667 Online
110070 Solutions
New Discussion

awk script problem

 
SOLVED
Go to solution
Asad Malik
Frequent Advisor

awk script problem

Hi
I type this on command line and get the desired output
#cat /var/adm/syslog/syslog.log |awk '$1 == "Mar" && $2 == "12" {print}'

This will print messages for Mar 12

I put this in script called as chklog, and run it like "chklog Mar 12"and it does not work.

h=$1
k=$2
cat /var/adm/syslog/syslog.log |awk '$1 == "$h" && $2 == "$k" {print}'

nothing prints.

Any suggestion
7 REPLIES 7
Madhu Sudhan_1
Respected Contributor

Re: awk script problem

Malik :
Try

h=$1
k=$2
awk '$1 == "$h" && $2 == "$k" {print $0}' /var/adm/syslog/syslog.log

...Madhu
Think Positive
Asad Malik
Frequent Advisor

Re: awk script problem

Hi Madhu
It does not work
Rita C Workman
Honored Contributor

Re: awk script problem

Well if your wanting to read particular days in syslog..here's a quick script:
#!/bin/sh
#
print -n "Enter 3char Month: "
read mon
print -n "Enter the day: "
read day
awk ' BEGIN {
while ( "cat '/var/adm/syslog/syslog.log' " | getline ) {
if ( $1 ~ '$mon' && $2 ~ '$day' ) print $0 }
} ' echo $0

This will allow you to select ANY day and have it echo to the screen...

/rcw
Rita C Workman
Honored Contributor

Re: awk script problem

oops...I missed a line..
before the if ($1 ... statement
enter on a line by itself
entries++

Sorry 'bout that,
/rcw
Rodney Hills
Honored Contributor
Solution

Re: awk script problem

The problem is occuring because you are using single quotes (') around the awk script. $h and $k are not expanded in that case. The proper way is to use the -v option of awk.

cat /var/adm/syslog/syslog.log | awk -v h=$1 -v k=$2 '$1==h && $2==k {print}'

The -v sets awk variables h and k to $1 and $2 (parameters on your shell script). The awk script can then compare $1 to h and $2 to k to look for matches.
There be dragons...
James R. Ferguson
Acclaimed Contributor

Re: awk script problem

Hi:

Try this:

# h=Mar
# k=12
# cat /var/adm/syslog/syslog.log|awk -v h=$h -v k=$k '$1==h && $2==k {print}'

...JRF...
Ed Ulfers
Frequent Advisor

Re: awk script problem

I had the same problem with some of my automated script, it stems from the single quote(') not evaluating the variable substitution.
Try the following:

h=\$1==\"$1\"
k=\$2==\"$2\"

awk "($h) && ($k) {print}"

This does work fine for me.
The single quote (') versus the double quote (") and backslashing characters (prefixing with \) can get very confusing, good luck in the future.
Put a smile on your users face, offer them a kiss (Hershey's Kiss).