I'm trying to figure out how to deal with whitespace in grep. How do I tell grep to find strings containing whitespace or tabs? The manual tells me nothing. \s seems to work for whitespace, and \S seems to work for non-whitespace, but it includes all whitespace characters (spaces AND tabs) and it doesn't work if I put it in brackets, treating the backslash and the \s as separate characters.

  • 1
    You'll need to get more clear with your question. Maybe put in an example of data and what you'd expect to match. – nik May 29 '13 at 2:51
  • Yes, it isn't entirely clear what you mean. What would you like to do precisely? And what does it mean to say that you put "in brackets, treating the backslash and the s as separate characters"? – ShankarG May 29 '13 at 5:18
  • 3
    "whitespace or tabs"? Tabs are whitespace. – grawity May 29 '13 at 8:32

Are you sure about that?

$ printf "a \tb\na b\na\tb" | grep '.\s*.'
a       b
a b
a       b

$ grep -V
grep (GNU grep) 2.14
Copyright (C) 2012 Free Software Foundation, Inc.

I.e., as shown, \s has matched both spaces and tabs -- I included the 'a' and 'b' just to highlight it.

What do you get?

  • -1, if I could: .\s*. also matches .., i.e., any two characters - and since all your strings have two characters, grep will match all of them. Should have used .\s+.. – muru May 27 '15 at 20:10
  • @muru, Please read the question carefully before you doing -1. You've completely missed the point. This is not a question regarding \s* or \s+. The OP thinks that \s is not working, I'm just emphasizing that it is working fine. Secondly, test your result before you post anything. Have you try to run printf "a \tb\na b\na\tb" | grep '.\s+.' before you post? Do you know why it is not working? -- you should use -E but failed to mentioned that. Next time, please think twice before showing off how kick-ass you are. – xpt May 28 '15 at 0:48
  • I regret what I said after cooling off. It's been a long and tiring day. Sorry. – xpt May 28 '15 at 1:16
  • OK, having cooled down, did you spot your mistake? (I can't do a -1, by the way) – muru May 28 '15 at 3:27
  • I've double-checked everything before I post and I've made my points clear. End of discussion. – xpt May 28 '15 at 15:52

In my experience grep works best with POSIX character classes - look up [[:space:]] for instance. I use grep extensively in some programs for user input validation and have never had a problem if I stuck to POSIX classes.

However, as commenters have noted, your question is not entirely clear.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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