Perl -ne captured group

Viewed 41

I want to output the captured group only.

input.txt

1xax1
1ybby1
9xcccx9

Command

perl -ne "/^.*x(.+)x.*$\// && print $1" input.txt

Output is all matching lines.

1xax1
9xcccx9

But I would expect ouly the captured group.

a
ccc

How to change my command??

1 Answers

Use single quotes (') around your script rather than double quotes ("):

perl -ne '/^.*x(.+)x.*$\// && print $1'

With double quotes, your shell interpolates $1 (which happens to be empty), so the one-liner that Perl receives is actually:

/^.*x(.+)x.*$\// && print

And print without arguments prints $_, which is the whole line.


Additionally, the current output of your script (with the single quotes) is:

accc

In order to easily add new lines, you could use the -l flag:

perl -nle '/^.*x(.+)x.*$/ && print $1' input.txt

which nicely outputs:

a
ccc

Incidentally, this will fix a bug with your current .*$\/: if the input file isn't finished by a newline, then your regex won't match the last line (because $\ is a newline here). But, even better to solve this last issue: you can omit the last part of your regex entirely (.*$\/ or .*$), since it doesn't change the outcome of the match (well, .*$\/ is buggy so it changes the outcome, but you get the idea):

perl -nle '/^.*x(.+)x/ && print $1'
Related