Grep not matching regular expression

2020-02-07 14:06发布

问题:

I'm strugging a bit to get matching results from grep.

Given the following input file's contents

{"foo":29, "bar":30}

and the following command grep -o '"[^"]+":[0-9]+' input.txt, I'm expecting two matching results. As far as I know it supports regular expressions, but I don't understand why grep doesn't return any results?

Other implementations of regexp are working fine (https://regex101.com/r/RcONXk/1).

回答1:

you can try this;

grep -oE '"[^"]+":[0-9]+'

Eg:

user@host:/tmp$ echo '{"foo":29, "bar":30}' | grep -oE '"[^"]+":[0-9]+'
"foo":29
"bar":30

man grep :

 -E, --extended-regexp
              Interpret PATTERN as an extended regular expression (ERE, see below).  (-E is specified by POSIX.)

Basic vs Extended Regular Expressions



回答2:

By default, grep does not match regex. Either use the e flag:

grep -oe 'pat' file

Or use egrep (automatically treats pattern as regex).

egrep -o 'pat' file


标签: regex grep