minor perl/awk tip
Robin Battey
zanfur at zanfur.com
Tue Jan 21 17:07:47 PST 2003
Thanks, didn't know about the -ne option.
My first draft used awk instead of perl, too, but I couldn't remember
offhand the syntax to change the field separator. But, after getting
off my duff and looking it up, here 'tis:
$ /sbin/ip addr show dev eth0 |
awk 'BEGIN { FS = "[ \t/]+" } /inet/ { print $3; }'
Whee-hah. And, for completeness' sake, here's an awk script that will
get all of them in that nicely formatted list:
$ /sbin/ip addr show |
awk 'BEGIN { FS = "[ \t/]+" }
/^[0-9]+:/ { printf "%s", $2; }
/inet/ { printf "\t%s\n", $3; }'
As usual, mangle the awk to get whatever output you desire.
Cheers!
-robin
P.S. the reason it's now $3 instead of $2 is because the default
behavior of awk is "special", and it strips leading and trailing
whitespace. That only happens when the value of FS is " " (a single
space). So, because I changed FS, $1 is *before* fir first space, and
is therefore blank -- making $2 "inet" and $3 the ip address.
On Tue, Jan 21, 2003 at 02:43:19PM -0800, Evan Martin wrote:
> On Tue, Jan 21, 2003 at 01:59:18PM -0800, Robin Battey wrote:
> > $ /sbin/ip addr show dev eth0 | perl -e 'while (<>) {
> > m#inet\s+(.+)/# and print "$1\n"; }'
>
> Equivalent perl (because that loop is such a common construct):
>
> perl -e 'while (<>) { foo; }'
> perl -ne 'foo;'
>
> Or even simpler, use awk:
> $ ip addr show dev eth0 | awk '$1 ~ /inet/ { print $2 }'
> 10.0.0.2/24
>
> or maybe just:
> $ ip addr show dev eth0 | awk '/inet/ { print $2 }'
>
> (...though that doesn't strip the mask like yours does.)
>
> --evan, who just helped out an awk tutorial and has awk on the brain.
>
> --
> Evan Martin
> martine at cs.washington.edu
> http://neugierig.org
--
Robin Battey
90CF 2E8F 8A96 D0C0 09A2 9CFE C130 6CD4 6DC3 6DCF
http://www.zanfur.com/zanfur.pub
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 230 bytes
Desc: not available
Url : http://mailman1.u.washington.edu/pipermail/linux/attachments/20030121/6954253e/attachment.bin
More information about the Linux
mailing list