Why are these regular expressions different?

2019-09-12 06:48发布

I am looking for lines that have an apostrophe in them and tried a few expressions that seemed identical to me; however, some worked and others didn't. Why did I get the following behavior:

egrep \' file      # works as expected

egrep "\'" file    # seems to return all lines

egrep "[\']" file  # works as expected

egrep '\'' file    # seems to be waiting for more input

标签: regex grep
2条回答
We Are One
2楼-- · 2019-09-12 07:43

I think you're over complicating it, if you're trying to match ' quote it in ":

echo "'" | grep "'"
查看更多
成全新的幸福
3楼-- · 2019-09-12 07:45

Single vs. double quotes have differences when it comes to escaping. Put echo in front to see what actually gets sent to egrep:

$ echo egrep \' file
egrep ' file
$ echo egrep "\'" file
egrep \' file
$ echo egrep "[\']" file
egrep [\'] file
$ echo egrep '\'' file
>

The last case is prompting for more input because you're still within a single-quoted expression: it's not an escaped quote (\') in single quotes (since that isn't how you escape single quotes.) It's a backslash between single quotes, with a trailing opening quote.

Incidentally, to escape a single quote in a single-quoted string, use a construction like this:

$ echo 'foo'\''bar'
foo'bar

What this is actually doing is putting a naked literal quote(\') between two single-quoted strings. These are then all implicitly concatenated together.

I have no idea why "\'" matches all lines (but it indeed seems to.)

查看更多
登录 后发表回答