Raza
Raza

Reputation: 394

Bash to find lines with exact one word?

I'm trying to write a bash script that takes a file name, and return lines that have one word. Here is sample text:

This has more than one word
There
is exactly one word in above line.
         White-space
in the start of the above line doesn't matter.
Need-some-help.

Output:

There
         White-space
Need-some-help.

I'm looking into using a combination SED and Regex.

Note: I cannot using anything else (it has to be a bash script, without custom modules), so suggesting that wouldn't help.

Upvotes: 1

Views: 4151

Answers (5)

Karoly Horvath
Karoly Horvath

Reputation: 96266

If words can contain any non-whitespace characters, then:

grep -E '^\s*\S+\s*$'

or

sed -E '/^\s*\S+\s*$/!d'

or

sed -n -E '/^\s*\S+\s*$/p'

Upvotes: 6

glenn jackman
glenn jackman

Reputation: 247012

If you have awk available: awk 'NF==1'

sed: delete any line with a "non-space space non-space" sequence sed '/[^ ] +[^ ]/d'

Upvotes: 4

gustavotkg
gustavotkg

Reputation: 4399

Well You could just delete lines which contain a char + space + char using sed.

#!/bin/bash
echo "This has more than one word
There
is exactly one word in above line.
         White-space
in the start of the above line doesn't matter.
Need-some-help." | sed '/\S \S/d' -

Upvotes: 1

Daniel Brockman
Daniel Brockman

Reputation: 19290

Assuming you can use grep (one of the most common tools used in shell scripts):

#!/bin/bash
grep '^ *[^ ]\+ *$' "$@"

Upvotes: 0

FailedDev
FailedDev

Reputation: 26940

^\s*\b[a-zA-Z.-]+\s*$

For the regex part and assuming you are searching the file line by line this regex will only match if there is exactly one word in the line.

Upvotes: 0

Related Questions