How to sort the contents of a file in place by column?


I have a file that has multiple columns separated by spaces. eg:

data1 data2 data3 data4
val1 val2 val3 val4 

I need to sort a file based on values ​​in different columns, for example, sometime based on the value of column 1, sometime based on the value of col2, etc.

I was thinking of a sort command, but couldn't figure out how to use it to accomplish this.

Thanx,

+5
source share
3 answers

It’s easy if you refuse on-site sorting:

sort -k 1 original > by_col_1
sort -k 2 original > by_col_2
+10
source

"", , . , -k:

: --key=2,2' ( -k 2,2 ').

.

+2

To sort the file in place, try vim-way:

$ ex -s +'%!sort -k1' -cxa file.txt

Alternatively use a parameter -olikesort -k1 in.txt -o out.txt

0
source

All Articles