awk - 使用 awk (gawk) 进行数字排序

标签 awk gawk

试图解决一个 question ,我写了以下gnu-awk脚本并遇到排序问题( 应该 已阅读手册)。

从手册:

Because IGNORECASE affects string comparisons, the value of IGNORECASE also affects sorting for both asort() and asorti(). Note also that the locale's sorting order does not come into play; comparisons are based on character values only.



这是建议的解决方案:
awk '{
    lines[$0]=length($0)
}
END {
    for(line in lines) { tmp[lines[line],line] = line }
    n = asorti(tmp)
    for(i=1; i<=n; i++) {
        split(tmp[i], tmp2, SUBSEP); 
        ind[++j] = tmp2[2]
    }
    for(i=n; i>0; i--)
        print ind[i],lines[ind[i]]
}' file
aaaaa foo 9
aaa foooo 9
aaaa foo 8
aaa foo 7
as foo 6
a foo 5
aaaaaaa foooo 13

我尝试添加 0 以强制数字类型,但是无法达到所需的输出。有没有办法在 awk/gawk 中模拟数字排序? ?

输入文件:
aaa foooo
aaaaaaa foooo
a foo
aaa foo
aaaaa foo
as foo
aaaa foo

期望输出:
aaaaaaa foooo
aaaaa foo     # Doesnt matter which one comes first (since both are same size)
aaa foooo     # Doesnt matter which one comes first (since both are same size)
aaaa foo
aaa foo
as foo
a foo

脚本输出中显示的数字仅用于说明如何进行排序。

最佳答案

看这个例子,Jaypal,你会得到:

kent$  cat f
3333333
50
100
25
44

kent$  awk '{a[$0]}END{asorti(a,b);for(i=1;i<=NR;i++)print b[i]}' f          
100
25
3333333
44
50

kent$  awk '{a[$0]}END{asorti(a,b,"@val_num_asc");for(i=1;i<=NR;i++)print b[i]}' f
25
44
50
100
3333333

关于awk - 使用 awk (gawk) 进行数字排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22666799/

相关文章:

regex - 在 bash 中解析类似 .csv 的文件

awk - 是否有 INT_MIN 和 INT_MAX 等价的 awk?

bash - 如何将 bash 变量作为 awk 参数的值传递?

regex - 与 awk 一起使用的正则表达式中的量词表现出意外

linux - awk/sed/grep 删除与另一个文件中的字段匹配的行

sed - awk, sed : one liner command for removing spaces from _all_ file names in a given folder?

linux - 使用 Linux 工具对文件的列进行排序

bash - awk 前的令人困惑的反斜杠,这是什么意思?

database - 如何使用 AWK 附加文本

bash - 如何按编号的百分比拆分文件。线?