开发者

Unix grep a string then only show the string in the list

Can anyone help to show me how to do this.

I use netstat to find out how many servers are currently connected to my servers, and I've got the following list, server001 and 002 has a number of services connected to myse开发者_Python百科rver01

myserver01.1050    server001.com.51535 64860      0 49680      0 ESTABLISHED
myserver01.1050    server001.com.36565 64860      0 49680      0 ESTABLISHED
myserver01.1050    server002.com.35262 64860      0 49680      0 ESTABLISHED
myserver01.1050    server002.com.41700 64860      0 49680      0 ESTABLISHED
myserver01.1050    server002.com.36525 64860      0 49680      0 ESTABLISHED
myserver01.1050    server002.com.54575 64860      0 49680      0 ESTABLISHED
myserver01.1050    server001.com.44401 64860      0 49680      0 ESTABLISHED
myserver01.1050    server001.com.47922 64860      0 49680      0 ESTABLISHED
myserver01.1050    server001.com.57080 49680      0 49680      0 ESTABLISHED

Can anyone tell me how can I grep or sort the list , which I could get a unique server name, something like the one below

myserver01.1050    server001.com
myserver01.1050    server002.com

Thanks


$ cut -d'.' -f1-3 input | sort | uniq
myserver01.1050    server001.com
myserver01.1050    server002.com

and using uniq -c you can get a count as well

$ cut -d'.' -f1-3 input | sort | uniq -c
      5 myserver01.1050    server001.com
      4 myserver01.1050    server002.com


This is a little ugly, but it works (6333197.txt containing your netstat output):

$ cat 6333197.txt | awk -F '.' '{print $1"."$2"."$3}' | sort -u

-F defines the input field separator, (awk man page)


cat netstat.txt | tr -s ' ' | cut -d" " -f2 | cut -d. -f1 | sort -u


It can all be done in 1 line awk command like this:

awk '{gsub(/\.[0-9]*$/, "", $2); serv[$2]=$1;} END{n=asorti(serv, dest); for (i = 1; i <= n; i++) print serv[dest[i]] " " dest[i];}' file.txt

OUTPUT (with above input):

myserver01.1050 server001.com
myserver01.1050 server002.com


Try this:

  $ grep myserver01.1050 logfile | \
    grep ' server' | \
    awk -F\. '{print $1, $2}' | \
    sort -u

Although I can't tell whether you want only the server name or only the pair of names. Kind of guessing, so sorry if I misinterpreted the question.


That's a version using sed and sort -u:

sed 's/^\(\S\S*\s\s*\S\S*\)\.[0-9][0-9]*\s.*/\1/' filename | sort -u

resp. with GNU version of sed ans sort -u:

sed -r 's/^(\S+\s+\S+)\.[0-9]+\s.*/\1/' filename | sort -u


Using sed and sort:

sed 's/\(.*\)\..*/\1/'  filename | sort -u
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜