How to use named regex groups in ack output?

南楼画角 提交于 2019-12-20 10:37:26

问题


Suppose I have a foo.txt file with the following content:

[2010-11-13 12:00:02,656]
[2010-11-13 12:00:02,701]
[2010-11-13 12:00:02,902]

When I ack for the date portion with the following, it works:

ack "(?P<foo>\d{4}-\d{2}-\d{2})" foo.txt --output "\$1"

2010-11-13
2010-11-13
2010-11-13

But when I try to use --output with the named group "foo", I cannot get it to work:

ack "(?P<foo>\d{4}-\d{2}-\d{2})" foo.txt --output "(?P=foo)"

(?=foo)
(?=foo)
(?=foo)

Any help is greatly appreciate it. Thanks so much.


回答1:


ack "(?P<foo>\d{4}-\d{2}-\d{2})" foo.txt --output "\$+{foo}"

(?P=foo) only works inside the regular expression (it's the named equivalent of \1). $+{foo} is the named equivalent of $1.

Also, with most shells, single quotes will help you avoid extra backslashes:

ack '(?P<foo>\d{4}-\d{2}-\d{2})' foo.txt --output '$+{foo}'


来源:https://stackoverflow.com/questions/4222727/how-to-use-named-regex-groups-in-ack-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!