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 .

Tutorial details
Difficulty level Easy
Root privileges No
Requirements awk and bash
Est. reading time N/A
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:

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

Sample outputs:

Unix is Best.
Outer space .

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 2 comments so far... add one


CategoryList of Unix and Linux commands
Disk space analyzersdf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
2 comments… add one
  • Seshadri Nov 12, 2012 @ 6:05

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

    awk ‘NF ==3’ filename

    • vaibhav kanchan Dec 13, 2012 @ 7:01

      Hi Seshadri,

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

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum