Operating System - HP-UX
1833777 Members
1992 Online
110063 Solutions
New Discussion

conditional awk statement

 
SOLVED
Go to solution
Jaris Detroye
Frequent Advisor

conditional awk statement

Is it possible to use and 'if' clause with in awk?

If so, could someone provide me with an example.

I am parsing a log file and I want to save a line in one variable if it starts with 'CMD:' (yes I am reading the cron log) and another if it does not.

Any ideas?
7 REPLIES 7
Steven E. Protter
Exalted Contributor

Re: conditional awk statement

I'm not sure if this is what you want but.

http://forums1.itrc.hp.com/service/forums/questionanswer.do?threadId=251166

Stuart has some very slick awk code in his post.

SEP
Steven E Protter
Owner of ISN Corporation
http://isnamerica.com
http://hpuxconsulting.com
Sponsor: http://hpux.ws
Twitter: http://twitter.com/hpuxlinux
Founder http://newdatacloud.com
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: conditional awk statement

Create a file my.awk:
{
if ($0 ~ /^CMD:/)
{
var1 = $0
}
else
{
var2 = $0
}
}

awk -f my.awk < infile

If it ain't broke, I can fix that.
Ian Dennison_1
Honored Contributor

Re: conditional awk statement

cat file1 |awk '$1 ~ /^CMD:/ {print "save line 1"} $1 !~ /^CMD:/ {print "save line 2"}'

Share and Enjoy! Ian
Building a dumber user
Michael Schulte zur Sur
Honored Contributor

Re: conditional awk statement

BEGIN{}
{
if (index($0,"CMD:)=1)
LINE1=$0
else
LINE2=$0;
}
END{}


Enough or more,

Michael
curt larson_1
Honored Contributor

Re: conditional awk statement

the syntax is
if (expr) statement
[else statement]

which gives you something like this

if ( outline != "" ) {
if ( type == "b" )
print something;
else
print somethingelse;
}
Michael Schulte zur Sur
Honored Contributor

Re: conditional awk statement

Hi,

it must of course be CMD:"

greetings,

Michael
Graham Cameron_1
Honored Contributor

Re: conditional awk statement

awk '
$0 ~ /CMD/ {printf "Line no %d contains CMD\n", NR}
$0 !~ /CMD/ {printf "Line no %d does not contain CMD\n", NR}
' /var/adm/cron/log

-- Graham
Computers make it easier to do a lot of things, but most of the things they make it easier to do don't need to be done.