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

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

To print lines that contain only three words using sed, grep, or awk, you can use a regular expression that matches lines with three word characters.

Here is an example of how to do this using each of these commands:

Using sed:

refer t‮o‬:lautturi.com
sed -n '/^\b[[:alpha:]]\+\b[[:alpha:]]\+\b[[:alpha:]]\+\b$/p' file.txt

Using grep:

grep '^\b[[:alpha:]]\+\b[[:alpha:]]\+\b[[:alpha:]]\+\b$' file.txt

Using awk:

awk '/^\b[[:alpha:]]\+\b[[:alpha:]]\+\b[[:alpha:]]\+\b$/' file.txt

In each of these examples, file.txt is the name of the file that you want to search. The regular expression ^\b[[:alpha:]]\+\b[[:alpha:]]\+\b[[:alpha:]]\+\b$ matches lines that contain only three word characters, where word characters are defined as alphabetical characters ([[:alpha:]]). The ^ and $ characters match the start and end of the line, respectively, and the \b characters match word boundaries.

You can modify the regular expression to match different types of words or to match lines with a different number of words. For example, to match lines with four words, you can use the following regular expression: ^\b[[:alpha:]]\+\b[[:alpha:]]\+\b[[:alpha:]]\+\b[[:alpha:]]\+\b$.

For more information about using regular expressions with sed, grep, and awk, you can consult the documentation for these commands and refer to resources on regular expression syntax.

Created Time:2017-10-29 22:08:59  Author:lautturi