Karthik
Karthik

Reputation: 105

Regular expression to match a pattern inside awk command

I need to write a regular expression to match the following pattern :

fltr_desc_name

that is.. "fltr" followed by an underscore followed by any number of words separated by underscore.

for example: I need a regular expression to match the following :

fltr_desc_name
fltr_nameone_nametwo
fltr_level_name_desc

and I am using it inside an "if" statement in "awk": for ex:

awk '/Transformation/ { if ($4=="Filter" && $5=="fltr_*") print $4,$5 }' filename  

please help me in writing the regular expression and tell me how to use regular expression inside an "if" condition inside "awk" command. Thank you.

Upvotes: 8

Views: 50034

Answers (6)

Wayne Doyle
Wayne Doyle

Reputation: 251

Need to use tilde character ~/ / in matching regular expressions in awk, i.e.

if ($5 ~ /fltr_*/)

Upvotes: 25

Ed Morton
Ed Morton

Reputation: 204558

awk '/Transformation/ && $4=="Filter" && $5~/^fltr_[[:alpha:]_]+/ { print $4,$5 }' filename

Upvotes: 8

Anders Johansson
Anders Johansson

Reputation: 4016

You could use

awk '/Transformation/ && $4=="Filter" && match($5, /^fltr_[A-Za-z_]+/) { print $4,$5 }' filename

No need to use an if statement, you can just use multiple matching conditions as per above. match returns the match location of the regex ^fltr_[A-Za-z_]+ in $5, or 0 if there is none. 0 evaluates to false and anything else to true.

Upvotes: 7

og Grand
og Grand

Reputation: 114

Try this

^fltr[_\d\w]+$

It will take all, you need.

Upvotes: 0

selltheworld
selltheworld

Reputation: 1

you could just use fltr_\w+

if you need a good program for writing and testing regex. try this one: http://gskinner.com/RegExr/

Upvotes: 0

sharp12345
sharp12345

Reputation: 4498

fltr_[a-zA-Z_]+[a-zA-Z]

or if you want to match from string start to string end only:

^fltr_[a-zA-Z_]+[a-zA-Z]$

Upvotes: 1

Related Questions