【发布时间】:2014-05-05 04:44:43
【问题描述】:
为了解决question,我编写了以下gnu-awk 脚本并遇到了排序问题(应该先阅读手册)。
来自手册:
因为 IGNORECASE 影响字符串比较,所以 IGNORECASE 的值 还会影响 asort() 和 asorti() 的排序。另请注意, 语言环境的排序顺序不起作用;比较是基于 仅针对字符值。
这是建议的解决方案:
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
脚本输出中显示的数字仅用于说明排序是如何完成的。
【问题讨论】:
-
您尝试过使用
sort之类的东西吗?你在哪里定义SUBSEP?期望的输出是什么? -
底部的文字是输入还是输出?您想按末尾的数字对这些行进行排序吗?
-
@AlexejMagura
SUBSEP是一个awk内置函数。他试图避免sort。这就是重点。 -
@TomFenech 他试图按行的长度进行排序,这些数字仅用于说明为什么 awk 以它的方式对行进行排序。
-
@EtanReisner 谢谢。这就是 input 文件?