为什么我不能将 ^s 与 grep 一起使用? [英] Why can't I use ^s with grep?
问题描述
以下两个正则表达式都适用于我.
Both of the regexes below work In my case.
grep s
grep ^[[:space:]]
然而,以下所有这些都失败了.我在 git bash 和 putty 中都试过了.
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.
如何使用 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
,您将匹配以空格开头的字符串,因为 \
将被解析为文字 字符.
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
这篇关于为什么我不能将 ^s 与 grep 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!