Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Perl -ne captured group

I want to output the captured group only.

input.txt

1xax1
1ybby1
9xcccx9

Command

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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??

>Solution :

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'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading