Michael
Michael

Reputation: 573

Bash getting and parsing results

I am trying to parse some results of

arp -a

and

Michael$ arp -a
? (10.254.0.1) at 0:1e:c9:bb:95:8c on en0 ifscope [ethernet]
? (10.254.0.2) at 0:1e:c9:bb:9a:8c on en0 ifscope [ethernet]
? (10.254.0.3) at 0:1e:c9:bb:9d:8c on en0 ifscope [ethernet]

How would I run a bash script to run arp -a and print out the IP for each returned?

Upvotes: 1

Views: 666

Answers (4)

Spencer Rathbun
Spencer Rathbun

Reputation: 14900

Here's another solution:

arp -a | cut -f 2 -d ' '

If you don't want the parenthesis:

arp -a | cut -f 2 -d ' ' | sed 's/[()]//g'

Or, to dump the ip addresses collected into an array:

ips=( $(arp -a | cut -f 2 -d ' ' | sed -r -e 's/[()]//g') )

To access:

echo ${ips[1]}

Upvotes: 1

Fritz G. Mehner
Fritz G. Mehner

Reputation: 17188

Pure Bash:

arp -a  | while read -a line ; do
  echo ${line[1]:1:-1}
done

Upvotes: 0

Dennis Williamson
Dennis Williamson

Reputation: 359955

For GNU grep (and some others which support PCRE):

arp -a | grep -Po '.*?\(\K.*?(?=\).*)'

AWK:

arp -a | awk -F '[()]' '{print $2}'

sed:

arp -a | sed 's/[^(]*(\([^)]*\)).*/\1/'

Perl:

arp -a | perl -lne 'print $1 if m{.*?\(\K(.*?)(?=\).*)}'

Upvotes: 3

Antoine Pelisse
Antoine Pelisse

Reputation: 13099

You can do it using awk:

arp -a | awk '{ gsub(/[()]/, "", $2); print $2; }'

Upvotes: 0

Related Questions