Operating System - HP-UX
1836230 Members
2010 Online
110096 Solutions
New Discussion

search string in awk program

 
SOLVED
Go to solution
Kris_5
Occasional Advisor

search string in awk program

Hi Folks,

I have to look for a particular charcter(#) in an awk variable (in awk program) and take decision based on it.

for e.g (Part of my awk program)

-----------------
if ( job_code != "" && script != "" && job_type != "" ) {
job_code1=system("echo "job_code"|grep \"#\"")
if (job_code1 != "" )
{
split(job_code,tag1,"#")
job_code2=tag1[1]
split(job_code2,tag2,"=")
job_code=tag2[1]
print "#/job_code="job_code"@"tolower(dbsid)"#hold#"
}
else {
print "#/job_code="job_code"@"tolower(dbsid)
}
print "#/job_type="job_type
print "#/script="script
---------------

for some reason, the variable job_type1 always not null. I have a suspicion that the command might be wrong. Can some body help me out. Thanks in adv.

Kris
4 REPLIES 4
harry d brown jr
Honored Contributor

Re: search string in awk program

Whereis your first "IF's" closing "}"??


live free or die
harry
Live Free or Die
James R. Ferguson
Acclaimed Contributor

Re: search string in awk program

Hi:

The value of 'job_code1' will be the exit status of the 'system' command -- either <0> or <1>. Does that help?

...JRF...
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: search string in awk program

Hi:

Why are you using grep within awk when awk can do pattern matching itself? Moreover, you are send a CONSTANT string into grep. You are always going to get the same answer!

A better approach might be:
if ($0 ~ /#/)
{
printf("I found it\n")
}
else
{
printf("Not there\n")
}

or if you already have your data in a named variable
if (job_code ~ /#/)
{

}
or
if (job_code !~ /#/) # does not match

Regards, Clay
If it ain't broke, I can fix that.
Anthony deRito
Respected Contributor

Re: search string in awk program

Not quite clear on what your looking to do but for what its worth...

a great way to parse through a text file and use a variable in an awk statement to identify the line to perform a substitution on is to use the ENVIRON function. For example, say you have a file called FILENAME. You wanted to search for all lines that had the contants of the HOST variable in its first field and based on that perform a substitution.

cat $FILENAME | awk -v var1="old" -v var2="new" '
(
if ($1 == ENVIRON["HOST"])
{
sub(var1,var2);
}
print
} '

Hope this helps!

Tony