【问题标题】:integer-only wildcards in grepgrep 中的整数通配符
【发布时间】:2019-07-08 22:09:04
【问题描述】:

我有一个命令可以输出如下所示的集合字符串:

json.formats[0]].url = "https://example.com/ar.html"
json.formats[1].url = "https://example.com/es.html"
json.formats[2s].url = "https://example.com/ru.html"
json.formats[3].url = "https://example.com/pt.html"
json.formats[73].url = "https://example.com/ko.html"
json.formats[1502].url = "https://example.com/pl.html"

(还有更多实例,但为了简单起见,它们已被删除)

我可以使用下面的命令

myCmd | grep -e 'json\.formats\[.*\]\.url\ \=\ '

但是我只希望通配符匹配整数,并丢弃非整数匹配。它给了我以下信息:

json.formats[0]].url = "https://example.com/ar.html"
json.formats[1].url = "https://example.com/es.html"
json.formats[2s].url = "https://example.com/ru.html"
json.formats[3].url = "https://example.com/pt.html"
json.formats[73].url = "https://example.com/ko.html"
json.formats[1502].url = "https://example.com/pl.html"

我真正想要的是:

json.formats[1].url = "https://example.com/es.html"
json.formats[3].url = "https://example.com/pt.html"
json.formats[73].url = "https://example.com/ko.html"
json.formats[1502].url = "https://example.com/pl.html"

谢谢:-)

【问题讨论】:

    标签: bash macos grep wildcard


    【解决方案1】:

    你可以使用:

    myCmd | grep -E 'json\.formats\[[[:digit:]]+\]\.url = '
    

    或:

    myCmd | grep -E 'json\.formats\[[0-9]+\]\.url = '
    

    [[:digit:]] 在大多数语言环境中等同于 [0-9]

    【讨论】:

    • 空字符串不是整数:您希望在该正则表达式中使用\+ 而不是*
    • \+ 需要 GNU grep,在 POSIX grep 中,等效的 BRE 将是 \{1,\}[0-9][0-9]* 但恕我直言,您应该只使用 -E+ 反正这也是 POSIX .
    • 谢谢埃德。我也更喜欢在 grep 中使用 -E
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-08
    • 2011-08-19
    • 2014-08-01
    相关资源
    最近更新 更多