LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   RE in commands like match() inside awk. (http://www.linuxquestions.org/questions/linux-newbie-8/re-in-commands-like-match-inside-awk-606228/)

stalin.varanasi 12-12-2007 02:53 AM

RE in commands like match() inside awk.
 
Hello,
I want to know what should I give in the regular expression inside match command in awk,to recognise a line having two patterns in order.

i.e for example,
My source file contains the following line:

"text text text pattern1 text text text pattern2
text text text text text text text pattern2"

i want recognise the 1st line only.

awk '{if(match($0,PATTERN1*PATTERN2))print $0}' source file

the above command is matching both.

Can any body tell me what should Regular expression should I put.

-Bourne.

osor 12-12-2007 02:38 PM

The regular expressions (at least they way you are using them) should be constants. Also, the use of the asterisk means you want to match zero or more of the preceding token (which happens to be a 1). This is most likely not what you had in mind. Additionally, the match() function is a GNU extension used for some more powerful constructs such as placing matches in an array. There is no reason to use it for something so simple as an “if” statement.

Anyway, here is the “corrected” version using gawk’s match():
Code:

awk '{if(match($0,/PATTERN1.*PATTERN2/))print $0}' file
And here is a much more elegant version (and a style you will most likely continue to see):
Code:

awk '/PATTERN1.*PATTERN2/{print $0}' file

stalin.varanasi 12-12-2007 11:31 PM

Hi OSR,
Thank you so much for your kind reply.Its working.
My main intention is to know how to write the regular expression only.But in my subject,I have put "RE in commands like match()" because I don't know whether regular expressions in ACTION part of gawk command are same as regular expressions in CONDITION part of gawk command or not.
Thanks once again.Your answer is very helpful to me.
-Stalin.


All times are GMT -5. The time now is 12:58 PM.