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

I have a sample data file:

ADVERTISEMENTS


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
DifficultyEasy (rss)
Root privilegesNo
Requirementsawk and bash
TimeN/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 SysAdmin, Linux/Unix, Open Source/DevOps topics:
CategoryList of Unix and Linux commands
File Managementcat
FirewallCentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig 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 VPNCentOS 8 Debian 10 Firewall Ubuntu 20.04

ADVERTISEMENTS
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>, <code>...</code> and <kbd>...</kbd> for code samples.