pogibas
pogibas

Reputation: 28379

awk partly string match (if column/word partly matches)

My dummy file looks like this:

C1    C2    C3    
1     a     snow   
2     b     snowman 
snow     c     sowman

I want to get line if there is string snow in $3. I can do this like this:

awk '($3=="snow" || $3=="snowman") {print}' dummy_file

But there should be more simpler way.

Upvotes: 124

Views: 327088

Answers (6)

WhiteRau
WhiteRau

Reputation: 857

It is far past the post date, but if you are not married to the awk and just want something to pull those lines, you can just use:

less -f dummy_file | grep snow

And I use less because cat does not handle UTF-8 very well

Note: this will check every line for the presence of snow

Upvotes: 0

Thunderbeef
Thunderbeef

Reputation: 1581

Also possible by looking for substring with index() function:

awk '(index($3, "snow") != 0) {print}' dummy_file

Shorter version:

awk 'index($3, "snow")' dummy_file

Upvotes: 61

Ahmed Masud
Ahmed Masud

Reputation: 22412

awk '$3 ~ /snow/ { print }' dummy_file 

Upvotes: 222

Endoro
Endoro

Reputation: 37589

GNU sed

sed '/\s*\(\S\+\s\+\)\{2\}\bsnow\(man\)\?\b/!d' file

Input:

C1    C2    C3    
1     a     snow   
2     b     snowman 
snow     c     sowman
      snow     snow     snowmanx

..output:

1     a     snow
2     b     snowman

Upvotes: 1

Chris Seymour
Chris Seymour

Reputation: 85883

Print lines where the third field is either snow or snowman only:

awk '$3~/^snow(man)?$/' file

Upvotes: 10

Ahmed Al Hafoudh
Ahmed Al Hafoudh

Reputation: 8429

Maybe this will help

http://www.math.utah.edu/docs/info/gawk_5.html

awk '$3 ~ /snow|snowman/' dummy_file

Upvotes: 13

Related Questions