Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only print matching lines in perl from the command line

Tags:

perl

I'm trying to extract all ip addresses from a file. So far, I'm just using

cat foo.txt | perl -pe 's/.*?((\d{1,3}\.){3}\d{1,3}).*/\1/'

but this also prints lines that don't contain a match. I can fix this by piping through grep, but this seems like it ought to be unnecessary, and could lead to errors if the regexes don't match up perfectly.

Is there a simpler way to accomplish this?

like image 535
jonderry Avatar asked Feb 24 '11 00:02

jonderry


People also ask

How do I get the matched pattern in Perl?

m operator in Perl is used to match a pattern within the given text. The string passed to m operator can be enclosed within any character which will be used as a delimiter to regular expressions.

What is =~ in Perl?

The Binding Operator, =~ Matching against $_ is merely the default; the binding operator ( =~ ) tells Perl to match the pattern on the right against the string on the left, instead of matching against $_ .

How do I use argv in Perl?

The @ARGV array holds the command line argument. There is no need to use variables even if you use "use strict". By default, this variable always exists and values from the command line are automatically placed inside this variable. To access your script's command-line arguments, you just need to read from @ARGV array.

How do I print a statement in Perl?

print operator in Perl is used to print the values of the expressions in a List passed to it as an argument. Print operator prints whatever is passed to it as an argument whether it be a string, a number, a variable or anything. Double-quotes(“”) are used as a delimiter to this operator.


1 Answers

Try this:

cat foo.txt | perl -ne 'print if s/.*?((\d{1,3}\.){3}\d{1,3}).*/\1/'

or:

<foo.txt perl -ne 'print if s/.*?((\d{1,3}\.){3}\d{1,3}).*/\1/'

It's the shortest alternative I can think of while still using Perl.

However this way might be more correct:

<foo.txt perl -ne 'if (/((\d{1,3}\.){3}\d{1,3})/) { print $1 . "\n" }'
like image 105
Mikel Avatar answered Oct 05 '22 14:10

Mikel