tags:

views:

130

answers:

2

I have a file that contains a lot of these

"/watch?v=VhsnHIUMQGM"

and I would like to output the letter code using a perl one-liner. So I try

perl -nle 'm/\"\/watch\?v=(.*?)\"/g' filename.txt

but it doesn't print anything.

What am I doing wrong?

+10  A: 

The -n option processes each line but doesn't print anything out. So you need to add an explicit print if you successfully match.

perl -ne 'while ( m/\"\/watch\?v=(.+?)\"/g ) { print "$1\n" }' filename.txt

Another approach, if you're sure every line will match, is to use the -p option which prints out the value of $_ after processing, e.g.:

perl -pe 's/\"\/watch\?v=(.+?)\"/$1//' filename.txt
PP
+4  A: 

Your regex is fine. You're getting no output because the -n option won't print anything. It simply wraps a while (<>) { ... } loop around your program (run perl --help for brief explanations of the Perl options).

The following uses your regex, but add some printing. In list context, regexes with the /g option return all captures. Effectively, we print each capture.

perl -nle 'print for m/\"\/watch\?v=(.*?)\"/g' data.dat
FM
Is it worth adding a `\n` so that captures are separated?
PP
@PP The `-l` option handles that.
FM