shell 脚本中的复杂排序 [英] Complex sorting in shell script

查看:27
本文介绍了shell 脚本中的复杂排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个满足提取要求的脚本,但我无法根据格式要求对结果进行排序.这是我的脚本:

I have written a script that fulfills the extraction requirement but I cannot sort the results according to the formatting requirements. This is my script:

awk '{print $9"  "$1}' ab.log | sort | uniq -c | awk '{print $2 "\t" $3}' | sort -nr

按降序显示状态码和IP地址;

It shows the status code and IP address in descending order;

404   89.86.144.219
404   81.192.148.245
.
.
403   172.6.0.3
403   129.16.26.39
402   145.8.0.9
402   256.23.4.57
.
.
401   126.158.20.9

但要求是:状态代码组必须按照哪个状态代码组出现的频率更高进行排序,并且 IP 地址必须按照每个组中出现的次数进行排序.

But the requirements are: status code groups have to be sorted by which status code group appears more often and the IP addresses have to be sorted by occurrence within each of the groups.

所以输出应该是:

404    127.0.0.1
404    xxx.xxx.xxx.xxx
.
.
200    xxx.xxx.xxx.xxx
200    xxx.xxx.xxx.xxx
.
.
403    xxx.xxx.xxx.xxx
403    xxx.xxx.xxx.xxx

如何根据上述要求对结果进行排序?

How can I sort the result according to the above requirements?

推荐答案

可能有一个惊人的单一命令可以用于此目的.然而,这里有一个使用 awk、sort 和 cut 的管道:

There is probably an amazing single command you can use for this. However here is a pipeline using awk, sort and cut:

$ awk '{a[$1]++;b[$0]=$1}END{for(i in b) printf "%-9d%s\n",a[b[i]],i}' | sort -k1,1nr -k2,2n -k3,3 | cut -c9-

使用 GNU awk,你甚至可以把它变成一个单一的命令,但它会开始看起来很乱

With GNU awk, you could even make it into a single command, but it just will start to look messy

这篇关于shell 脚本中的复杂排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆