Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

grep

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

)

like image 844
lightsong Avatar asked Mar 16 '12 11:03

lightsong


People also ask

How do you grep with additional lines?

For BSD or GNU grep you can use -B num to set how many lines before the match and -A num for the number of lines after the match.

How do I convert multiple spaces to single space in Unix?

Re: the echo $string | perl note: When IFS is at its default value, echo $string itself will replace runs of multiple spaces with a single space (along with other side effects, like replacing a wildcard in that string with a list of files) -- one needs to use echo "$string" to keep them in.

What does \s mean in grep?

' \s ' Match whitespace, it is a synonym for ' [[:space:]] '. ' \S ' Match non-whitespace, it is a synonym for ' [^[:space:]] '. For example, ' \brat\b ' matches the separate word ' rat ', ' \Brat\B ' matches ' crate ' but not ' furry rat '.

How do you grep for spaces?

If you want to allow for ANY space character (tab, space, newline, etc), then if you have a “grep” that supports EXTENDED regular expressions (with the '-E' option), you can use '[[:space:]]' to represent any space character.


3 Answers

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

If you want to catch 2 or more whitespaces.

like image 154
fancyPants Avatar answered Nov 01 '22 09:11

fancyPants


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.

like image 21
Ernest Friedman-Hill Avatar answered Nov 01 '22 10:11

Ernest Friedman-Hill


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
like image 45
Vijay Avatar answered Nov 01 '22 10:11

Vijay