Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort content of a file in-place by a column?


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,

like image 772
sud03r Avatar asked Jul 07 '09 10:07

sud03r


People also ask

How do you sort data in files?

Sort a File Numerically To sort a file containing numeric data, use the -n flag with the command. By default, sort will arrange the data in ascending order. If you want to sort in descending order, reverse the arrangement using the -r option along with the -n flag in the command.


2 Answers

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
like image 79
Matthew Flaschen Avatar answered Oct 12 '22 19:10

Matthew Flaschen


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.

like image 43
unwind Avatar answered Oct 12 '22 19:10

unwind