4

Both of the regexes below work In my case.

grep \s
grep ^[[:space:]]

However all those below fail. I tried both in git bash and putty.

grep ^\s
grep ^\s*
grep -E ^\s
grep -P ^\s
grep ^[\s]
grep ^(\s)

The last one even produces a syntax error.

If I try ^\s in debuggex it works.

Regular expression visualization

Debuggex Demo

How do I find lines starting with whitespace characters with grep ? Do I have to use [[:space:]] ?

Nicolas Seiller
  • 564
  • 1
  • 10
  • 20
  • 3
    Are you using quotes at all? Without quoting, bash will 'eat' the escape of `\s` and you will need a second `grep ^\\s ...` – guido Dec 20 '18 at 11:04
  • You're right ! with `\\s` it works ! But I don't get why ... Well if you put it as an answer I will accept it. – Nicolas Seiller Dec 20 '18 at 11:07
  • 2
    You should alway quote every argument to every command unless you have a specific reason not to and fully understand all the implications. Quote using `'` by default, then `"` if necessary (e.g. to let a shell variable expand) and finally no quote if absolutely necessary (e.g. to allow word splitting, globbing and file name expansion). – Ed Morton Dec 20 '18 at 15:56
  • Possible duplicate of [Bash Regular Expression -- Can't seem to match \s, \S, etc](https://stackoverflow.com/questions/18514135/bash-regular-expression-cant-seem-to-match-s-s-etc) – tripleee Apr 04 '19 at 03:59

1 Answers1

2

grep \s works for you because your input contains s. Here, you escape s and it matches the s, since it is not parsed as a whitespace matching regex escape. If you use grep ^\\s, you will match a string starting with whitespace since the \\ will be parsed as a literal \ char.

A better idea is to enable POSIX ERE syntax with -E and quote the pattern:

grep -E '^\s' <<< "$s"

See the online demo:

s=' word'
grep ^\\s <<< "$s"
# =>  word
grep -E '^\s' <<< "$s"
# =>  word
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    `\s` is a PRCE, not an ERE. It's supported by GNU `grep` but most other `grep` implementations will interpret `\s` as `s`. – Kusalananda Dec 20 '18 at 12:04
  • @Kusalananda I know, I meant a GNU grep. I only test with GNU grep, I am an Ubuntu user. Other implementations are too buggy from what I have seen for more than a year here on SO. – Wiktor Stribiżew Dec 20 '18 at 12:13
  • I don't even need any flag, it works with `grep '^\s'` – Nicolas Seiller Dec 20 '18 at 13:22
  • @NicolasSeiller True, but it is just for convenience. If you use `+` or `{}`, you won't have to escape them. – Wiktor Stribiżew Dec 20 '18 at 13:25
  • 1
    `\s` has nothing to do with EREs or BREs - it'll work as shorthand for `[[:space:]]` in any regexp flavor if your grep (or other tool) version supports that shorthand and if it doesn't then it won't. – Ed Morton Dec 20 '18 at 15:54