选择和排序 IP 地址保持整行

Uhc*_*iar 4 linux bash sort

所以我需要对 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
Run Code Online (Sandbox Code Playgroud)

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

    add method1 a
    add method2 e
    add method2 a
    add method5 j
    add method3 a
    add method1 e
Run Code Online (Sandbox Code Playgroud)

字段 4 将是:

    d other thing
    h other thing2
    d other thing2
    m other thing5
    d other thing3
    h other thing2
Run Code Online (Sandbox Code Playgroud)

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

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

Jam*_*ger 8

迟到的答案,但它可能会帮助某人。如果您有最新版本的 GNU sort(来自GNU coreutils 7.0或更高版本),您可以使用--version-sort(or -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
Run Code Online (Sandbox Code Playgroud)

运行此操作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
Run Code Online (Sandbox Code Playgroud)


meu*_*euh 5

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

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

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

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