Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What am I doing wrong in this Perl one-liner?

Tags:

perl

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?

like image 306
Sandra Schlichting Avatar asked Aug 28 '10 13:08

Sandra Schlichting


3 Answers

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
like image 103
PP. Avatar answered Sep 28 '22 06:09

PP.


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
like image 25
FMc Avatar answered Sep 28 '22 06:09

FMc


You can split the string on "=" instead of matching:

perl -paF= -e '$_= @F[1]' filename.txt
like image 32
Eugene Yarmash Avatar answered Sep 28 '22 08:09

Eugene Yarmash