Nicolas Seiller
Nicolas Seiller

Reputation: 624

Why can't I use ^\s with grep?

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:]] ?

Upvotes: 4

Views: 9883

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627022

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

Upvotes: 2

Related Questions