4

I need to parse the command arp -a to get only the ip of the device. Right now I have

arp -a | awk '{print $2}' | head -1

However this gives me

(192.168.1.71)

and I must remove the ( ) from the output. How can this be done?

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
Chen Yao
  • 43
  • 3
  • welcome to U&L, what do you meant by **get the only ip of the device** ? on most unix/linux system `arp -a` will give a random list of recently used IPs and MACs. – Archemar Jul 25 '19 at 06:36

3 Answers3

2

You could use the characters () as field separators instead of whitespace:

arp -a | awk -F'[()]' '{print $2}' | head -1
user4556274
  • 8,725
  • 2
  • 31
  • 37
1

using cut :

arp -a | awk '{print $2}' | head -1 | cut -d "(" -f 2 | cut -d ")" -f 1

Updating the answer as suggested in the comment:

cut explanation:

-d - acts as delimiter and splits the string on first occurrence of (

-f - selects the specified field. Here selects the 2nd part which would be x.x.x.x)

We give this output as input to next cut using |

cut -d ")" -f 1 - This again splits the input on ) and we select the first part i.e. Just the IP address.

HarshaD
  • 356
  • 1
  • 3
  • 9
0

tr is good at things like deleting unwanted characters:

$ tr -d '()' <<< '(192.168.1.1)'
192.168.1.1

So all told, it would be:

arp -a | awk '{print $2}' | head -1 | tr -d '()'
Jim L.
  • 7,188
  • 1
  • 13
  • 25