Pages

Sunday, May 8, 2016

sort command one liners


sort in default mode sorts the file in alphabetical order

# sort file_name

sort removes the duplicates using the -u option

# sort -u file_name

The default sort 'might' give incorrect result on a file containing only numbers, so to work bet on such file -n option can be used

# sort -n file_name

sort file numerically in reverse order using option -r

# sort -nr file_name

sort can sort multiple files as well.

# sort -n file_name1 file_name2

Sort can merge two files and remove duplicates

# sort -nu file_name 1 file_name 2

Sorting a file containing multiple fields, default sort will sort by first column

# sort file_name

sort file on the basis of 1st field delimited by “,”

# sort -t"," -k1,1 file_name
Where,
'-t' option is used to provide the delimiter in case of files with delimiter.
'-k' is used to specify the keys on the basis of which the sorting has to be done.
The format of '-k' is : '-km,n' where m is the starting key and n is the ending key.

Sorting file on the basis of the 2nd field delimited by “:”

# sort -t":" -k2,2 file_name

Sorting file on the basis of 2nd field , numerically:

# sort -t"," -k2n,2 file_name

Remove duplicates from the file based on 1st field delimited by “|”

# sort -t"|" -k1,1 -u file_name

Sort the file numerically on the 2nd field in reverse order delimited by “;”

# sort -t";" -k2nr,2 file_name

Sort the file alphabetically on the 1st field, numerically on the 2nd field delimited by “,”

# sort -t"," -k1,1 -k2n,2 file_name

sort a file based on the 1st and 2nd field, and numerically on 3rd field on  a file containing 5 columns:


# sort -t"," -k1,2 -k3n,3 file_name

Back To Top

No comments:

Post a Comment