Search code examples
grepnumbersmaxoutputnetstat

GREP - Search only in first n characters of each line, searching for number after special character


my first post here.

In summary: I have a netstat output, using "netstat -an" command in Windows, and I would like to get the top number of one of the columns.

The output of netstat is something like this:

  TCP    10.45.43.232:50387     10.42.48.61:902        ESTABLISHED
  TCP    10.45.43.232:50559     46.228.47.115:443      CLOSE_WAIT
  TCP    10.45.43.232:52501     10.48.48.128:3389      ESTABLISHED
  TCP    10.45.43.232:58000     10.46.48.243:63713     ESTABLISHED

The result I want is:

58000

That number is the biggest value on the second column, after the ":" character

So, in essence, I want a grep (and/or sed, awk, etc) which can search through a file, only look in the first 25 characters of each line, and get the highest number after a ":" character.

Tell me if you need more information, thanks in advance!


Solution

  • This can be an approach:

    netstat ... | sort -t':' -nrk2 | awk -F"[ :]" '{print $8; exit}'
    

    By pieces:

    Sort it based on : as delimiter and taking second column into account:

    $ netstat ... | sort -t':' -nrk2
      TCP    10.45.43.232:58000     10.46.48.243:63713     ESTABLISHED
      TCP    10.45.43.232:52501     10.48.48.128:3389      ESTABLISHED
      TCP    10.45.43.232:50559     46.228.47.115:443      CLOSE_WAIT
      TCP    10.45.43.232:50387     10.42.48.61:902        ESTABLISHED
    

    Print the biggest:

    $ netstat ... | sort -t':' -nrk2 | awk -F"[ :]" '{print $8; exit}'
    58000
    

    Or better, using Mark Setchell's approach to fetch the last item:

    $ netstat ... | sort -t':' -nrk2 | awk '{sub(/.*:/,"",$2); print $2; exit}'
    58000