如何根据字段的数值对文件进行排序?
示例file.txt
:
100 foo
2 bar
300 tuu
当使用sort -k 1,1 file.txt
时,行的顺序不会改变,尽管我们期望:
2 bar
100 foo
300 tuu
如何对包含的字段进行排序基于绝对数值的数字?
Example file.txt
:
100 foo
2 bar
300 tuu
When using sort -k 1,1 file.txt
, the order of lines will not change, though we are expecting :
2 bar
100 foo
300 tuu
How to sort a field consisting of numbers based on the absolute numerical value?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
查看排序手册页...
所以这是一个例子......
Take a peek at the man page for sort...
So here is an example...
如果您要对混合文本和文本的字符串进行排序,数字,例如滚动日志的文件名,然后使用
sort -n
排序无法按预期工作:在这种情况下,选项
-V
可以解决问题:来自手册页:
If you are sorting strings that are mixed text & numbers, for example filenames of rolling logs then sorting with
sort -n
doesn't work as expected:In that case option
-V
does the trick:from man page:
好吧,这里的大多数其他答案都指的是
但是,我不确定这是否适用于负数。以下是我在 Fedora 9 上使用排序版本 6.10 得到的结果。
输入文件:
输出:
显然不是按数值排序的。
然后,我想更精确的答案是使用
sort -n
但前提是所有值都是正数。PS:使用
sort -g
返回与此示例相同的结果编辑:
看起来区域设置会影响减号如何影响顺序(参见此处)。为了获得正确的结果,我刚刚做了:
Well, most other answers here refer to
However, I'm not sure this works for negative numbers. Here are the results I get with sort version 6.10 on Fedora 9.
Input file:
Output:
Which is obviously not ordered by numeric value.
Then, I guess that a more precise answer would be to use
sort -n
but only if all the values are positive.P.S.: Using
sort -g
returns just the same results for this exampleEdit:
Looks like the locale settings affect how the minus sign affects the order (see here). In order to get proper results I just did:
您必须使用数字排序选项:
You have to use the numeric sort option:
使用
sort -n
或sort --numeric-sort
。Use
sort -n
orsort --numeric-sort
.您必须执行以下命令:
sort -n -k1 filename
这样就可以了:)
You must do the following command:
sort -n -k1 filename
That should do it :)
谢谢你,皮吉尔蒙。
我试图制作一个 m3u 播放列表,对所有目录和子目录进行精确的字母排序,其中一些具有相同的名称和编号。
字母不是问题,数字才是问题。
之前:
成为
您的
LC_ALL=C sort -n
以更简单且正确的方式实现了这一点。我读了“排序”帮助/手册中的 LC_ALL=C 但没有太注意它(或者更确切地说不明白如何准确使用它)。结束代码:
将(给定的)音乐文件路径按树形顺序写入 m3u。
另一种选择是完全重新排列列表:
至少在这种情况下,这些东西目前对我来说似乎很有效。
Thank you pgilmon.
I was trying to make a m3u-playlist with precise alphabetical sorting allover dirs and subdirs of which some with the same name and numbered.
The alphabet wasn't the problem, the numbering was.
Before:
became
Your
LC_ALL=C sort -n
did the trick the easier and correct way. I read the LC_ALL=C in the 'sort' help/man but hadn't payed too much attention to it (or rather didn't understand how to exactly use it).End code:
writes (the given) music file paths in their tree order to the m3u.
The alternative is a completely shuffled list:
At least these things seem to work well for me for the moment in this context.
使用 sort -nr 按降序排序。请参阅
排序
请参阅上面的手册页以获取更多参考
Use sort -nr for sorting in descending order. Refer
Sort
Refer the above Man page for further reference