Blog

03/06/2019

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:

#!/bin/bash
# AWK NF if condition (awk '{ if ( NF == 3 ) print } ' $_input) emulation using bash 
# Author: nixCraft <sxi.io>
# -----------------------------------------------------------------------------------
_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 .

Posted by: SXI ADMIN

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

20/08/2019

Start your Bitcoin Exchange with our Software

Start your Bitcoin Exchange with our Software Setup your white label bitcoin exchange right away. Or create your own cryptocurrency using...
14/08/2019

How to KVM, QEMU start or stop virtual machine from command line (CLI)

KVM or Kernel Based Virtual Machine is a popular virtualization technology. It allows you to run virtual guest machines over a host machine. To start...
14/08/2019

How to Docker backup Saving and restoring your volumes

Running a Docker volume backup First, we spin up a temporary container, and we mount the backup folder and the target Docker volume to this container....