为什么我不能在grep中使用^ \ s? [英] Why can't I use ^\s with grep?

查看:147
本文介绍了为什么我不能在grep中使用^ \ s?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下两种正则表达式都可以正常工作.

Both of the regexes below work In my case.

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

但是所有下面的失败.我在git bash和腻子中都尝试过.

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.

如果我在debuggex中尝试 ^ \ s ,它将起作用.

If I try ^\s in debuggex it works.

Debuggex演示

如何找到以 grep 开头的空格字符的行?我必须使用 [[:: space:]] 吗?

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

推荐答案

grep \ s 为您工作,因为您输入的内容包含 s .在这里,您对 s 进行转义,并且它与 s 匹配,因为它没有被解析为与正则表达式转义符匹配的空格.如果使用 grep ^ \\ s ,则将匹配以空格开头的字符串,因为 \\ 将被解析为文字 \ char

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.

一个更好的主意是使用 -E 启用POSIX ERE语法并引用该模式:

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

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

请参见在线演示:

s=' word'
grep ^\\s <<< "$s"
# =>  word
grep -E '^\s' <<< "$s"
# =>  word

这篇关于为什么我不能在grep中使用^ \ s?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆