lightsong
lightsong

Reputation: 391

How to find lines that contain more than a single whitespace between strings in unix?

I have lines like

1|Harry|says|hi
2|Ron|says|bye
3|Her   mi oh ne|is|silent
4|The|above|sentence|is|weird

I need a grep command that'll detect the third line.

This is what Im doing.

grep -E '" "" "+' $dname".txt" >> $dname"_error.txt"

The logic on which I'm basing this is, the first white space must be followed by one or more white spaces to be detected as an error.

$dname is a variable that holds the filename path.

How do I get my desired output?

( which is

      3|Her   mi oh ne|is|silent

)

Upvotes: 6

Views: 16953

Answers (4)

user918938
user918938

Reputation:

If you want 2 or more spaces, then:

grep -E "\s{2,}" ${dname}.txt >> ${dname}_error.txt

The reason why your pattern doesn't work is because of the quotation marks inside. \s is used for [space]. You could actually do the same thing with:

grep -E '  +' ${dname}.txt >> ${dname}_error.txt

But it's difficult to tell exactly what you are looking for with that version. \s\s+ would also work, but \s{2,} is the most concise and also gives you the option of setting an upper limit. If you wanted to find 2, 3, or 4 spaces in a row, you would use \s{2,4}

Upvotes: 2

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

Just this will do:

grep "  " ${dname}.txt >> ${dname}_error.txt

The two spaces in a quoted string work fine. The -E turns the pattern into an extended regular expression, which makes this needlessly complicated here.

Upvotes: 5

Vijay
Vijay

Reputation: 67211

below are the four ways.

pearl.268> sed -n 's/  /&/p' ${dname}.txt >> ${dname}_error.txt
pearl.269> awk '$0~/  /{print $0}' ${dname}.txt >> ${dname}_error.txt
pearl.270> grep '  ' ${dname}.txt >> ${dname}_error.txt
pearl.271> perl -ne '/  / && print' ${dname}.txt >> ${dname}_error.txt

Upvotes: 2

fancyPants
fancyPants

Reputation: 51868

grep '[[:space:]]\{2,\}' ${dname}.txt >> ${dname}_error.txt

If you want to catch 2 or more whitespaces.

Upvotes: 7

Related Questions