15

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
  • Note: Using named regex groups is dependent on your underlying Perl. Named regex groups were introduced in Perl 5.10, but if you're using ack with an older Perl (since ack works with Perl 5.8, too), then they won't work. Apr 30, 2012 at 11:40

1 Answer 1

20
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}'
2
  • 4
    That P part of (?P<name>…) is optional. That is, a simple (?<name>…) is plenty.
    – tchrist
    Nov 19, 2010 at 11:56
  • Note: This answer does not work as of at least 2019. See github.com/beyondgrep/ack3/issues/284.
    – hftf
    Mar 14, 2023 at 3:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.