How to match words and ignore multiple spaces?

Use tr with its -s option to compress consecutive spaces into single spaces and then grep the result of that:

$ echo 'Some   spacious  string' | tr -s ' ' | grep 'Some spacious string'
Some spacious string

This would however not remove flanking spaces completely, only compress them into a single space at either end.

Using sed to remove the flanking blanks as well as compressing the internal blanks to single spaces:

echo ' Some   spacious  string' |
sed 's/^[[:blank:]]*//; s/[[:blank:]]*$//; s/[[:blank:]]\{1,\}/ /g'

This could then be passed through to grep.


Use Regex operator + to indicate one or more of the preceding token, space in this case. So the pattern would be \+:

echo "Ambari Server      running"  | grep -i "Ambari \+Server \+running"

I would suggest to use character class [:blank:] to match any horizontal whitespace, not just plain space, if you are unsure:

echo "Ambari Server      running"  | grep -i "Ambari[[:blank:]]\+Server[[:blank:]]\+running"

On the other hand, if you want to keep just one space between words, use awk:

echo "Ambari Server      running"  | \
    awk '$1=="Ambari" && $2=="Server" && $3=="running" {$1=$1; print}'
  • $1=="Ambari" && $2=="Server" && $3=="running" matches the desired three fields

  • {$1=$1} rebuilds the record with space as the new separator

  • {print} prints the record