I should have gone to bed hours ago.
George Geller wrote:
> Thanks to all you guys who got back to me about the my little perl script.
> I owe each of you a cup of coffee or something.
>
> My hat is off to John H. Robinson, IV who reduced it to a one-liner.
How about another one:
#!/usr/bin/perl -T -w
$ENV{PATH}="";
qx(/sbin/ifconfig eth0) =~ m/inet addr:([^ ]*)/ && print "$1\n" || print "No
match.\n";
exit 0;
__EXIT__
You can remove the $ENV{PATH}=""; line if you remove the -T from the #!
line. The exit 0 is not really required, either. If you change the eth0
to a -a, then it will report the IP of the first reported interface. My
testing indicated that lo is usually not the first.
> Overall, I liked Chris Grau's the best for reasons that were already
> discussed.
I don't like his RE, though it has a good anchor and matches an IP well,
but not perfectly. It will match an illegal octet. I'm also not a big
fan of the xms flags to the m//, especially in this case where the only
whitespace used was in a character class (x), no anchors were used (m),
and wild-card . was not used (s).
If you want truly idiomatic perl, we don't need all the spaces, and can
take advantage that we will be printing something regardless if there is
a match or not. We also shrink the RE slightly:
perl -e'print qx(/sbin/ifconfig eth0)=~/t addr:([^ ]*)/?"$1\n":"No match.\n"'
I cannot ``factor out'' the \n without using more characters. It does
not matter, as we have gotten to less than 80 characters, including the
perl invocation.
Replace the <"No match.\n"> with <exit 1> for more character savings, and to
make it more UNIX-like. Truly evil perl, but it works.
If we can live with a silent report upon failure, and are happy with an
exit code of 0 in either case, we can get more savings still!
perl -e'print "$1\n" if qx(/sbin/ifconfig eth0)=~/t addr:([^ ]*)/'
If you really want to use Chris's RE, let's improve it slightly:
perl -e'print "$1\n" if qx(/sbin/ifconfig eth0)=~/inet
addr:([0-9]{1,3}(\.[0-9]{1,3}){3})/'
As a bonus, the last part of the IP is in $2!
% perl -e'print "$2\n" if qx(/sbin/ifconfig -a)=~/inet
addr:([0-9]{1,3}(\.[0-9]{1,3}){3})/'
.106
Wow, I have spent way too much time on this.
-john
--
[email protected]
http://www.kernel-panic.org/cgi-bin/mailman/listinfo/kplug-lpsg