Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to search for a field that only has spaces. When counting, this two commands gave me different results:

grep "^\s*$" -E -c
grep "^(\s*$)" -E -c

Another thing. What is the correct way to say "spaces only or other thing":

grep "^(\s*$|STRING)" -E -c


grep "(^\s*$|^STRING)" -E -c

Or they are equivalent?

share|improve this question
up vote 5 down vote accepted

Plain grep doesn't understand \s or parentheses.(*) You want grep -P if available, or grep -E/egrep and write \s out as [ ^I] (where ^I is Tab; grep without -P doesn't understand \t either). Additionally, with double quotes some shells will process the \s and leave behind just s; you should always use single quotes with regexes from the shell, except for when you actually need to interpolate a variable (e.g. something like '^\s*'"$foo"'\s+\(', switching quoting in mid-parameter).

The alternatives in your second example (again, with -P and single quoting instead of double) do the same thing. The former is technically better because grep won't backtrack as much, but practically it won't matter.

(*) pedantry: backslashed parens will work, again requiring single quoting so the shell doesn't eat the backslashes. egrep is usually easier.

share|improve this answer
While the general advice to use single quotes is right, in this particular case, it doesn't matter: ) and | are not single-character variables, so the shell won't interpolate $) or $|; and "\s" expands to \s, the backslash inside double quotes is retained except before "$\`. – Gilles Apr 17 '11 at 18:02
@geekosaur I was using the -E option but i forgot to include it here. I will edit the post. In this case why the two options give me different results? The single vs double-quotes can influence this? – user6678 Apr 17 '11 at 18:02
@Gilles: that turns out to depend on the shell; I've just gotten 3 different behaviors from three different shells. – geekosaur Apr 17 '11 at 18:16
@user6678: see my reply to Gilles; it depends on the shell (but it appears that in bash the double quotes should be okay; it's still a bad habit that can lead to problems in the future, though). \s is not supported by grep -E in any version of GNU grep I have available (checked on OSX and Ubuntu Maverick). That said, I would expect them to behave the same (if incorrectly), and they do so here. – geekosaur Apr 17 '11 at 18:21
Newer versions of plain grep actually do understand \s. grep -c '\s' <<<' ' == 1. – Quolonel Questions Mar 11 '15 at 11:17

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.