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

StackOverflow https://stackoverflow.com/questions/22657830

Domanda

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!

È stato utile?

Soluzione

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

Altri suggerimenti

if the output has leading space/tabs:

netstat...|awk -F':|\\s*' '{p=$4>p?$4:p}END{print p}'

if there is no leading spaces:

netstat ..| awk -F':|\\s*' '{p=$3>p?$3:p}END{print p}'

I would go with this:

netstat -an | awk '{sub(/.*:/,"",$2); if($2>max)max=$2} END{print max}'

The sub() part strips all characters up to and including a colon, off the second field thereby extracting the port. If that is greater than max, max is updated. At the end, max is printed.

Here is yet another way using GNU awk:

netstat ... | awk '{split($2,tmp,/:/); a[tmp[2]]++}END{n=asorti(a);print a[n]}' 
  • We split the second field of second column (delimited by :) in a tmp array
  • We populate the values as keys in array a.
  • In the END we use GNU awk asorti function which sorts the keys and print the highest.

You can also do it with coreutils alone:

netstat ... | cut -d: -f2 | cut -d' ' -f1 | sort -nr | head -n1

Output:

58000
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top