I have a file which has multiple columns, whitespace separated. e.g:
我有一个文件,它有多个列,空格分隔。例如:
data1 data2 data3 data4 val1 val2 val3 val4
I need to sort the file based on values in different columns, i.e sometime based on value of column 1 sometime based on value of col2 and so on.
我需要根据不同列中的值对文件进行排序,有时基于第1列的值,有时基于col2的值,依此类推。
I thought of sort command but couldn't figure out how to use it to accomplish this.
我想到了sort命令,但无法弄清楚如何使用它来实现这一目标。
Thanx,
3 个解决方案
#1
10
It's easy if you give up on sorting in place:
如果你放弃原地排序很容易:
sort -k 1 original > by_col_1
sort -k 2 original > by_col_2
#2
2
Sort has built-in understanding of "keys", which is the part of the line that is used to do the comparison. By default, the key is the entire line, but this can be changed using the -k
option:
Sort具有对“keys”的内置理解,这是用于进行比较的行的一部分。默认情况下,键是整行,但可以使用-k选项更改:
Example: To sort on the second field, use
--key=2,2' (
-k 2,2').示例:要对第二个字段进行排序,请使用--key = 2,2'( - k 2,2')。
By default, keys are separated by the transition between non-blank and blank characters.
默认情况下,键由非空白字符和空白字符之间的过渡分隔。
#3
0
To sort file in-place, try vim-way:
要对文件进行就地排序,请尝试使用vim-way:
$ ex -s +'%!sort -k1' -cxa file.txt
Alternatively use -o
parameter like sort -k1 in.txt -o out.txt
或者使用-o参数,例如sort -k1 in.txt -o out.txt
#1
10
It's easy if you give up on sorting in place:
如果你放弃原地排序很容易:
sort -k 1 original > by_col_1
sort -k 2 original > by_col_2
#2
2
Sort has built-in understanding of "keys", which is the part of the line that is used to do the comparison. By default, the key is the entire line, but this can be changed using the -k
option:
Sort具有对“keys”的内置理解,这是用于进行比较的行的一部分。默认情况下,键是整行,但可以使用-k选项更改:
Example: To sort on the second field, use
--key=2,2' (
-k 2,2').示例:要对第二个字段进行排序,请使用--key = 2,2'( - k 2,2')。
By default, keys are separated by the transition between non-blank and blank characters.
默认情况下,键由非空白字符和空白字符之间的过渡分隔。
#3
0
To sort file in-place, try vim-way:
要对文件进行就地排序,请尝试使用vim-way:
$ ex -s +'%!sort -k1' -cxa file.txt
Alternatively use -o
parameter like sort -k1 in.txt -o out.txt
或者使用-o参数,例如sort -k1 in.txt -o out.txt