试图解决一个 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/