Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

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

like image 863
Nicolas Seiller Avatar asked Sep 06 '25 07:09

Nicolas Seiller


1 Answers

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
like image 196
Wiktor Stribiżew Avatar answered Sep 08 '25 00:09

Wiktor Stribiżew