Search code examples
linuxbashwc

Print only lines with more than $1 words


I'd like to print only the lines with $1 number of words or more. Please help.

while read line ; do
    echo $line | wc -w 
done t1.txt

Solution

  • Assuming you're defining a word as characters delimited by spaces, then awk would do this easily:

    awk -v COUNT=$1 'NF>COUNT' t1.txt
    

    It passes the first arg in as an awk variable named count, and prints rows where the number of space delimited fields is above the count provided.

    e.g.

    $ echo $COUNT
    3
    $ cat t1.txt
    hey
    hey hey hey hey hey
    hey hey hey
    hey hey hey
    hey hey hey hey hey
    hey hey hey hey hey
    hey hey hey
    
    $ awk -v COUNT=$COUNT 'NF>COUNT' t1.txt
    hey hey hey hey hey
    hey hey hey hey hey
    hey hey hey hey hey