Reputation: 573
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
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
Reputation: 17188
Pure Bash:
arp -a | while read -a line ; do
echo ${line[1]:1:-1}
done
Upvotes: 0
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
Reputation: 13099
You can do it using awk:
arp -a | awk '{ gsub(/[()]/, "", $2); print $2; }'
Upvotes: 0