≡ Menu

Linux / Unix: Sed / Grep / Awk Print Lines If It Got 3 Words Only

I have a sample data file:

This is a test.
Unix is Best.
No Linux is the Best.
Space in simple understanding is an area or volume.
Outer space .

I need the output:

Unix is Best.
Outer space .

How do I print all lines that have three (3) words only?

The awk command is well suitable for this kind of pattern processing text file. Awk set the variable called NF. It is set to the total number of fields in the input record. So if NF equal to three print the line. The syntax is as follows:

awk '{ if ( NF == 3 ) print } ' /path/to/input

It is also possible to emulate awk command output using a shell script while loop and IFS (internal field separator) in loops:

# AWK NF if condition (awk '{ if ( NF == 3 ) print } ' $_input) emulation using bash 
# Author: nixCraft <www.cyberciti.biz>
# -----------------------------------------------------------------------------------
while IFS= read -r line
	set -- $line
	[ $# -eq $_word ] &&  echo "$line" 
done < "$_input"

Sample outputs:

Unix is Best.
Outer space .
Share this tutorial on:

Like this? Follow us on Twitter OR support us by using Patreon

{ 2 comments… add one }
  • Seshadri November 12, 2012, 6:05 am

    Since the newer awks “print” by default, you can just do:

    awk ‘NF ==3’ filename

    • vaibhav kanchan December 13, 2012, 7:01 am

      Hi Seshadri,

      It should be awk ‘NF == 3’ filename. Yes it will work and no need to use printf too.

Security: Are you a robot or human?

Leave a Comment

You can use these HTML tags and attributes: <strong> <em> <pre> <code> <a href="" title="">

   Tagged with: , , , , ,