3

I'm trying to format arp -a output to my liking. For example at the moment it outputs:

MyRouter (172.16.3.x) at XX:XX:XX:XX:XX:XX [ether] on eth0
PC1 (172.16.3.x) at XX:XX:XX:XX:XX:XX [ether] on eth0
PC2 (172.16.3.x) at XX:XX:XX:XX:XX:XX [ether] on eth0

But I want it to output something like:

MyRouter;172.16.3.x;XX:XX:XX:XX:XX:XX
PC1;172.16.3.x:XX:XX:XX:XX:XX:XX
PC2;172.16.3.x;XX:XX:XX:XX:XX:XX

If I echo one of the lines with a BAD sed command that I created, it'll format the output to my liking but I can't use it on an arp -a command

Command:

$ echo "MyRouter (172.16.3.x) at XX:XX:XX:XX:XX:XX [ether] on eth0" | sed 's/ (/;/g' | sed 's/) at /;/g' | sed 's/ \[.*//g'
MyRouter;172.16.3.x;XX:XX:XX:XX:XX:XX

But how can I format the arp -a output like this?

Oli
  • 289,791
  • 117
  • 680
  • 835
Reno
  • 33
  • 3
  • You're on the right track. To get it to sed, you pipe arp -a to sed like so: `arp -a | sed 's/ (/;/g' | sed 's/) at /;/g' | sed 's/ \[.*//g'` – Terrance Apr 07 '16 at 16:23
  • Just to avoid giving unuseful answers, what's the reason you can't you use `sed` exactly? – kos Apr 07 '16 at 16:28
  • I have No idea why it didn't work the first time, but thank you Terrance, this works. And also the selected answer works as well. – Reno Apr 07 '16 at 16:35

2 Answers2

4

Give this one sed command version a try:

arp -a | sed 's/^\([^ ][^ ]*\) (\([0-9][0-9.]*[0-9]\)) at \([a-fA-F0-9:]*\)[^a-fA-F0-9:].*$/\1;\2;\3/'
Jay jargot
  • 526
  • 2
  • 6
2

With awk:

arp -a | awk -F'[ ()]' '{OFS=";"; print $1,$3,$6}'

Output:

MyRouter;172.16.3.x;XX:XX:XX:XX:XX:XX
PC1;172.16.3.x;XX:XX:XX:XX:XX:XX
PC2;172.16.3.x;XX:XX:XX:XX:XX:XX

-F'[ ()]': sets field separators to whitespace, ( and )

OFS=";": sets Output Field Separator to ;

Cyrus
  • 5,394
  • 2
  • 19
  • 31