skip to Main Content

If i execute the below comment, The result will be like this 8060 0.0.0.0

netstat -antup | grep nginx |awk ‘{print $4 "t" $5 }’ | cut -d ":" -f2

But I want the result to be like this 8060

2

Answers


  1. Not sure what the orignial response from the command is, but just cut the response again is one way

    netstat -antup | grep nginx |awk '{print $4 "t" $5 }' | cut -d ":" -f2 | cut -d " " -f1
    
    Login or Signup to reply.
  2. Deconstructing the command you provided, netstat -antup prints these information:

    $ netstat -antup
    Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
    tcp        0      0 127.0.0.1:8060         0.0.0.0:*               LISTEN      XYZ/nginx
    ...
    

    You want just the "8060", which is the port, nginx is listening to.

    The next part was fine. grep nginx |awk '{print $4}' gives you the corresponding Local Address. You don’t need the "t" $5 part, as the Foreign Address is not relevant here.

    The intermediary result should look like this:

    $ netstat -antup | grep nginx | awk '{print $4}'
    127.0.0.1:8060
    

    Now the port ist the last part after a ":". Be aware, that IPv6 addresses also contain ":"s. So i’d suggest to cut the very last one instead of the 2nd.
    You can do so, by reverting the output, cutting the first bit and reverting again:

    $ netstat -antup | grep nginx | awk '{print $4}' | rev | cut -d":" -f1 | rev
    8060
    

    et voila. the desired output

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search