Matthew L. Abrasax Matthew L. Abrasax - 4 months ago 18
Perl Question

Grab text between identifiers while escaping a hyphen "-" in perl

I'm attempting to grab the text of a line after the "A. " until the end of the line. I've tried:

perl -ne 'print if /A[.] /../\R/' test.txt > test2.txt

Where I thought the "\R" would match the end of a line. However when the line contains a hyphen "-", the output does not stop at the end of the line, instead prints the next lines until the hyphens stop.

An example line from test.txt that fails is as follows:

A. -rw-r-----, -r--------

The intended test2.txt output is:

-rw-r-----, -r--------

I'm getting the following bad output:

-rw-r-----, -r--------B. -rw-r--r--, -r--r--r--C. -rw-r--r--, -r--------D. -rw-r--rw-, -r-----r--E. -rw-------, -r--------: C

The following:

perl -nle 'print if /A[.] (.*)/' test.txt > test2.txt
produces the same result as the command i provided above, but the output is still not ending at the end of the line when a hyphen is present.


I think you're looking for

perl -nle'print $1 if /A[.] (.*)/'

You could also use

perl -ne'print /A[.] (.*)/s'


perl -ne'print if s/^(.*?)A[.] //'

$ cat test.txt
A. -rw-r-----, -r--------
B. -rw-r-----, -r------w-
C. -rw-r-----, -r------x-
A. -rw-r-----, -r------y-
D. -rw-r-----, -r------z-

$ perl -nle'print $1 if /A[.] (.*)/' test.txt
-rw-r-----, -r--------
-rw-r-----, -r------y-

$ perl -ne'print /A[.] (.*)/s' test.txt
-rw-r-----, -r--------
-rw-r-----, -r------y-

$ perl -ne'print if s/^(.*?)A[.] //' test.txt
-rw-r-----, -r--------
-rw-r-----, -r------y-