bash linux bash按字典顺序“排序” - 零问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3107312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
linux bash 'sort' in dictionary order - problem with zeros
提问by michael
I'm seeing something strange with 'sort' in RedHat Enterprise Linux 5 x86_64 and in Ubuntu 9.1. I'm using bash.
我发现 RedHat Enterprise Linux 5 x86_64 和 Ubuntu 9.1 中的“排序”有些奇怪。我正在使用 bash。
First here's what I think is right to expect from sort using dictionary order:
首先,我认为使用字典顺序排序是正确的:
[stauffer@unix-m sortTrouble]$ cat st1
1230
123
100
11
10
1
123
1230
100
[stauffer@unix-m sortTrouble]$ cat st1
1230
123
100
11
10
1
123
1230
100
[stauffer@unix-m sortTrouble]$ sort st1
1
10
100
100
11
123
123
1230
1230
[stauffer@unix-m sortTrouble]$ sort st1
1
10
100
100
11
123
123
1230
1230
[stauffer@unix-m sortTrouble]$
[stauffer@unix-m sortTrouble]$
Now here's what happens when there's a second column (tab-delimited, even though it looks messy here):
现在这是当有第二列时会发生什么(制表符分隔,即使这里看起来很乱):
[stauffer@unix-m sortTrouble]$ cat st2
1230 1
123 1
100 1
11 1
10 1
1 1
123 1
1230 1
100 1
[stauffer@unix-m sortTrouble]$ cat st2
1230 1
123 1
100 1
11 1
10 1
1 1
123 1
1230 1
100 1
[stauffer@unix-m sortTrouble]$ sort st2
100 1
100 1
10 1
1 1
11 1
1230 1
1230 1
123 1
123 1
[stauffer@unix-m sortTrouble]$ sort st2
100 1
100 1
10 1
1 1
11 1
1230 1
1230 1
123 1
123 1
Notice how the sort order for column 1 is different now. '11' gets put correctly after '1', but '10' and '100' do not. Similarly for '1230'. It seems like zero causes trouble.
请注意现在第 1 列的排序顺序有何不同。'11' 在 '1' 之后被正确放置,但 '10' 和 '100' 没有。'1230' 也类似。似乎零会导致麻烦。
This behavior is inconsistent, and it causes problems when using 'join' because it expects dictionary sorting.
这种行为是不一致的,并且在使用 'join' 时会导致问题,因为它需要字典排序。
On Mac OSX 10.5, the st2 file sorts like st1 in the first column.
在 Mac OSX 10.5 上,st2 文件在第一列中的排序类似于 st1。
Am I missing something, or is this a bug?
我错过了什么,还是这是一个错误?
Thanks, Michael
谢谢,迈克尔
采纳答案by Paused until further notice.
The sort can be performed the way you want by restricting the key to the column you're interested in:
通过将键限制为您感兴趣的列,可以按照您想要的方式执行排序:
sort -k1,1 inputfile
回答by Anycorn
from the man page
从手册页
-b, --ignore-leading-blanks
ignore leading blanks
-g, --general-numeric-sort
compare according to general numerical value
-n, --numeric-sort
compare according to string numerical value
ex:
前任:
andrey@localhost:~/gamess$ echo -e "1\n2\n10" | sort
1
10
2
andrey@localhost:~/gamess$ echo -e "1\n2\n10" | sort -g
1
2
10

