选择并排序 IP 地址,保持整行

选择并排序 IP 地址,保持整行

所以我需要对 IP 地址进行排序,然后按它们对我的行进行排序。

我可以使用以下命令对文件中的 IP 地址进行排序:sort -n -t . -k1,1 -k2,2 -k 3,3 -k4,4

如果我的文件看起来像:

    add method1 a.b.c.d other thing
    add method2 e.f.g.h other thing2
    add method2 a.b.c.d other thing2
    add method5 j.k.l.m other thing5
    add method3 a.b.c.d other thing3
    add method1 e.f.g.h other thing2

但在这种情况下,字段 1 将是:

    add method1 a
    add method2 e
    add method2 a
    add method5 j
    add method3 a
    add method1 e

字段 4 将是:

    d other thing
    h other thing2
    d other thing2
    m other thing5
    d other thing3
    h other thing2

我应该如何以及使用什么工具来对我的 IP 地址进行排序,然后根据它们对我的线路进行排序。提前致谢。

编辑:示例已修改。有几行具有相同的 IP 地址,但文本不同且顺序随机。

答案1

迟到的回答,但它可能对某人有帮助。如果您有最新版本的 GNU sort(来自GNU coreutils 7.0或更高版本),您可以使用--version-sort(或-V) 选项,它将对 IPv4 地址执行正确的操作。假设输入:

add method1 10.1.2.3 other thing
add method2 10.10.20.30 other thing2
add method2 10.1.2.3 other thing2
add method5 10.2.8.9 other thing5
add method3 10.1.2.3 other thing3
add method1 10.10.20.30 other thing2

运行这个sort -k 3 -V将产生:

add method1 10.1.2.3 other thing
add method2 10.1.2.3 other thing2
add method3 10.1.2.3 other thing3
add method5 10.2.8.9 other thing5
add method1 10.10.20.30 other thing2
add method2 10.10.20.30 other thing2

答案2

该脚本使用 awk 将字段 3 中的 IP 地址复制到带有“%”分隔符的行开头,然后对第一个字段中的 IP 地址进行排序,然后删除添加的部分。

awk '{print $3 " % " $0}' |
sort -t. -n -k1,1 -k2,2 -k3,3 -k4,4 |
sed 's/[^%]*% //'

如果带有 ip 地址的字段不是常量,您可以在每行上自动检测它。将上面的 awk 替换为:

awk '{ for(i=1;i<=NF;i++)
         if($i~/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/)break;
       print $i " % " $0
     }' |

答案3

这是预期的,请确保您理解该-t选项(man sort:字段分隔符)。您想要使用的命令涉及清楚的仅 IP 地址。

一个快速但肮脏的解决方案可能是先将文件中的空格转换为点.,然后排序(您可能希望稍后撤消转换,不包括 IP 地址)

sed -i.bak 's/ /./g' data.log
sort -n -t . -k2,2 -k3,3 -k4,4 -k5,5 data.log

请注意,我移动了索引。试一试。

相关内容