Thursday, September 18, 2014

sort command examples

Sort command in Unix:

The sort command sorts lines of all the named files together and writes the result on the standard output. Comparisons are based on one or  more  sort  keys  extracted from  each line of input. By default, there is one sort key, the entire input line. Lines are ordered  according to the collating sequence of the current locale.

Examples:

ubuntu:user% cat line
test1|test2|test3
one|two|three
dev|stag|prod
solaris|linux|unix
oracle|sybase|mysql

//Sorted by 1st column
ubuntu:user% sort -t'|' -k1 line
dev|stag|prod
one|two|three
oracle|sybase|mysql
solaris|linux|unix
test1|test2|test3

//Sorted by 2nd column
ubuntu:user% sort -t'|' -k2 line
solaris|linux|unix
dev|stag|prod
oracle|sybase|mysql
test1|test2|test3
one|two|three

//Reverses the order
ubuntu:user% sort -rt'|' -k1 line
test1|test2|test3
solaris|linux|unix
oracle|sybase|mysql
one|two|three
dev|stag|prod

//Sorts by number
ubuntu:user% sort -nt'|' -k4 line
solaris|linux|unix|1
test1|test2|test3|2
one|two|three|3
dev|stag|prod|4
oracle|sybase|mysql|5

//Using sort in combination with other commands using pipe
ubuntu:user% cat line | egrep "dev|oracle|one" | sort -nt '|' -k4
one|two|three|3
dev|stag|prod|4
oracle|sybase|mysql|5

//If the delimeter is not specified, then sort command takes the entire line as a string and sorts it based on the first column
ubuntu:user% sort line
dev|stag|prod|4
one|two|three|3
oracle|sybase|mysql|5
solaris|linux|unix|1
test1|test2|test3|2



No comments:

Post a Comment