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

You can use a combination of the sed, grep, and awk utilities to print lines that contain only 3 words. Here are examples of how you can do this using each utility:

  1. sed: The following sed command prints lines that contain exactly 3 words:
sed -n '/\b\w\+\b \b\w\+\b \b\w\+\b/p' file.txt
  1. grep: The following grep command prints lines that contain exactly 3 words:
grep '^\b\w\+\b \b\w\+\b \b\w\+\b\b' file.txt
  1. awk: The following awk command prints lines that contain exactly 3 words:
awk 'NF==3 {print $0}' file.txt

Note: In each of these commands, file.txt should be replaced with the name of the file you want to process. Also, \b is a word boundary, \w is a word character (letters, digits, and underscores), and \+ means “one or more.”

Leave a Comment