egrep -o:Linux和MacOS中的不同行为

时间:2018-05-14 09:07:16

标签: regex shell scripting grep posix-ere

我有两个脚本,我想在Linux机器和MacOS机器上运行。但 { "id": 6, "channel_id": 2, "channel": { "id": 2, "tags": [ "new" ] }, } 命令的不同行为使这些脚本生成不同的输出。

特别是,当我在Linux(Ubuntu)上使用egrep时会发生这种情况:

egrep

这就是我在MacOS上使用$ echo ".test" | egrep "[a-zA-Z0-9]*" .test $ echo ".test" | egrep -o "[a-zA-Z0-9]*" test $ 时会发生的事情

egrep

第一个行为是我所期望的,第二个行为(空输出)是意外的。也许这是在MacOS下使用$ echo ".test" | egrep "[a-zA-Z0-9]*" .test $ echo ".test" | egrep -o "[a-zA-Z0-9]*" $ 选项实现egrep的错误?

或者,如果第二种行为也是正确的,你知道如何为第二种情况获得相同的行为吗?

我试着查看两个命令的相应-o页面,这是从Linux手册页中提取的:

man

,这是从MacOS的手册页中提取的:

 -o, --only-matching
        Print only the matched (non-empty) parts of a matching line, with each 
        such part on a separate output line.

尽管描述看起来有点不同,但两个选项的含义似乎相同,那么为什么 -o, --only-matching Prints only the matching part of the lines. 在MacOS中表现不同?我没有考虑这个命令的任何微妙方面吗?

1 个答案:

答案 0 :(得分:2)

这取决于不同的grep实现如何处理空匹配([a-zA-Z0-9]*与空字符串匹配)。

我在Unix& Linux上写过a longer text about this

简而言之,是否应返回所有空匹配?有无数的这样的比赛。