views:

329

answers:

2

Hi all,
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.

I thought of sort command but couldn't figure out how to use it to accomplish this.

Thanx,

+5  A: 

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
Matthew Flaschen
thanx,,, it was -k option.. one more thing can it work with column separator other than space..
Neeraj
Yes, use the -t option. You should check out *man sort*.
Lars Haugseth
+2  A: 

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:

Example: To sort on the second field, use --key=2,2' (-k 2,2').

By default, keys are separated by the transition between non-blank and blank characters.

unwind