简体   繁体   中英

Count the number of lines having more than N words using AWK

I am having a sample file sample.txt having the contents as below:

this is me
hello
my name is x
awk tutorials
unable to get this right

I want to count the number of lines with more than N words. Let's consider N=3

Hence, the desired output is 2 (3rd line and 5th line).

I have tried the below code:

cat sample.txt | awk 'BEGIN{count=0}{"NF>3" then count++} END{print count}'

My output is always 5 (which is the number of lines in the file; the output remains the same even when N is changed from 3 to 8, indicating that the condition is always True).

Could you please try following.

 awk -v num="3" 'NF>num{count++} END{print count}'  Input_file

OR

awk 'NF>3{count++} END{print count}'  Input_file

Problem with OP's code attempt:

  • OP's method of condition "NF>3" then count++ is not right.
  • In spite of looking for lines where NF>3 its increasing value of count every time and hence each time output is 5 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM