AWK: how to select lines by the number of words in one field

awktext processing

Here's a text file I have:

1|this|1000
2|that|2000
3|hello|3000
4|hello world|4000
5|lucky you|5000
6|awk is awesome|6000
.
.
.

How do I only print the lines that have two and only two words (line 4 and 5) in the $2?

This is what I have tried but it counts the number of letters instead of words:

awk -F"|" '{if(length($2==2) print $0}'

Best Answer

You can use the return value of the awk split function:

$ awk -F'|' 'split($2,a,"[ \t]+") == 2' file
4|hello world|4000
5|lucky you|5000
Related Question