Operating System - HP-UX
1834297 Members
2136 Online
110066 Solutions
New Discussion

regular expression in awk

 
SOLVED
Go to solution
David Gartner
Occasional Contributor

regular expression in awk

Hi

I'm using awk to search for a particular pattern in a text file. The script is very basic as I'm just trying some things currently.

/^2..abc...ANI$/ {print "some text" }

I save the above in a file called awktest and run it using;

awk -f awktest inputfile

Now the problem I am having occurs while I try and anchor the regex with the $ It doesn't produce what I'm expecting

a sample input line in my file would be

2lmabcXYZANI 12345 890 NO

I just want the field "2lmabcXYZANI" but I get no output.
hmmmmm.........
5 REPLIES 5
A. Clay Stephenson
Acclaimed Contributor

Re: regular expression in awk

Hi David,
You are operating under a misconception about how awk works. In your example, the input record (line) would have to begin with '2' and the line would have to end with 'ANI'. 'ANI' in the middle of the input record does not match. What you need to do is remove the '$' and thus the input record passes the match.
You then would enter a block to process that line and find where your patern begins and ends and print that section. I would use the the built-in functions index or match to find the positions and substr to extract the desired positions followed by a print or printf. You just need a bit more practice with it.

This should get you started, Clay
If it ain't broke, I can fix that.
federico_3
Honored Contributor

Re: regular expression in awk

try like this:

/^2/ && /ANI$/ {print "some text" }


federico

Vincent Stedema
Esteemed Contributor
Solution

Re: regular expression in awk


If you're using a space as the FS:

$1 ~/^2.*ANI$/ {print}
or
$1 ~/^2..abc...ANI$/ {print}

Vincent
Stefan Schulz
Honored Contributor

Re: regular expression in awk

If you like to get the first field i would use the following:

awk '/^2..abc...ANI/ {print $1} ' inputfile

this should give you the desired output.

Hope the helps. Stefan
No Mouse found. System halted. Press Mousebutton to continue.
Carlos Fernandez Riera
Honored Contributor

Re: regular expression in awk

Use substr function of awk:

awk '

substr ( $1, 1,2 ) == "xxxx" && substr ($1,13,4 ) { print .....}'

See man awk for substr parameters .
unsupported