2

I want to print the IP and the Port separately using netstat command,

I tried this:

netstat -nat | awk '{print $4}'

But It gives me that:

192.168.1.213:40405

I want something like that:

First the IP: 192.168.1.213

and with another command the Port: 40405

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
Asis
  • 65
  • 2
  • 12

3 Answers3

4

You could always pipe it into cut:

# Just the IP:
$ netstat -nat | awk '{print $4}' | cut -d ":" -f1

# Just the port:
$ netstat -nat | awk '{print $4}' | cut -d ":" -f2
Mureinik
  • 297,002
  • 52
  • 306
  • 350
2

If you want them as different commands, you could use sed to do it like:

netstat -nat | awk '{print $4}' | sed -e 's/:.*//' # gives IP only
netstat -nat | awk '{print $4}' | sed -e 's/.*://' # gives port only

Depending on how you're using it, you could store it in a bash variable and accomplish the same thing while access it like

both=$(netstat -nat | awk '{print $4}')
ip=${both%%:*}
port=${both##*:}
Eric Renouf
  • 13,950
  • 3
  • 45
  • 67
1

i am using zsh shell and i am getting port in new line with the same command

netstat -nat | awk '{print $4}'

maybe try changing your profile preference

Lalit Yadav
  • 889
  • 9
  • 16