Operating System - HP-UX
1820710 Members
2842 Online
109627 Solutions
New Discussion юеВ

Re: awk and pattern matching

 
SOLVED
Go to solution
Anthony deRito
Respected Contributor

awk and pattern matching


How do you perform pattern matching with awk using a variable instead of plain text?

example:

awk '{$4="match_this_text" print .....}'

In the example above I want to use a variable name for the string "match_this_text".

Tony

7 REPLIES 7
Jdamian
Respected Contributor

Re: awk and pattern matching

use the match() function:

awk '{ if (match($4,"match_this_text") ... }'
Ian Dennison_1
Honored Contributor
Solution

Re: awk and pattern matching

export MATCHTXT="match_this_text"

awk -v matchvar=$MATCHTXT '$4 == matchvar { print "found it!"}

Alternatively, put literal text in -v portion of awk line.

Share and Enjoy! Ian
Building a dumber user
Leif Halvarsson_2
Honored Contributor

Re: awk and pattern matching

Hi,

Have you tried just to match the two variables, it should be possible (if you dont have a very old version of awk).

$4 == { do something }
MANOJ SRIVASTAVA
Honored Contributor

Re: awk and pattern matching

ls -l | awk '{if($5=="May" && $6=="7") print $NF }'

will print all files created witht the date May 7th


I hope this clears the syntax.


Manoj Srivastava
Rodney Hills
Honored Contributor

Re: awk and pattern matching

The pattern match operator is "~" when put in the pattern field-

Here is an example-

awk '$4~/ab.*yz/{print ...}'

HTH

-- Rod Hills
There be dragons...
Ian Lochray
Respected Contributor

Re: awk and pattern matching

export TEXT_STR=your_string
awk -v match_this_text=${TEXT_STR} '{if($4 == match_this_string) print .... }' file_name
Rolf Modin
Advisor

Re: awk and pattern matching

I solved a problem where I wanted to find all lines in the /var/adm/syslog/mail.log file, belonging to mail to or from a specific e-mail address. There are two different lines for every message. The common information is a message ID in one field.

I made an awk script that generated a new awk script that had all the pattern matches as strings generated from variables in the first script.

Something like:

awk '/to:e-mail addres/ {print "/"$3"/ {what should be done }' > scriptfilename.awk

The final script was made to look someting like:
/first found message ID/ {what should be done}
/other found message ID/ {what should be done}
...

The generated script was run with
awk -f scriptfilename.awk inputfile

With BEGIN and END filters You could also generate BEGIN and END in the second awk script.

Good luck!
Rolf