Wednesday, July 18

Linux/Unix sort command examples

This is a small tutorial on how to use sort command to sort a file. Sorting is very useful when dealing with DB files, CSV, xls, log files in fact a text file too. By default sort command will sort according to alphabets. First sort tries to sort according to single character, if it finds the first character same in two lines, then it moves to sort second character. Suppose I have a following word list in a file
cat filename.txt
abc
cde
hij
klm
kle
ble
This will be sorted first with first char. When it finds both the char same in this example klm and kle start with same characters, so it tries to sort with third character which is different in them. The output of sort  as below
sort filename.txt
abc
ble
cde
hij
kle
klm

Sort command syntax
#sort filename.txt
Example1: Sort a given file according to alpha-bates
 #sort filename.txt
Example2: I have a file with host names in third column, how can i sort them according to this column?. Use -k for sorting according to column
#sort -k3 filename.txt
The above command will sort according to third column.
Example3:I want to sort /etc/passwd file according to home directories but my sort is not working how can i sort them?. by default sort will take space/tabs as field separators. But in /etc/passwd file the field separator is : so we have to mention this one when sorting a file. This can be done with -t option
#sort -t: -k6 /etc/passwd
Example4: I want to sort according to number, suppose i want to sort /etc/passwd file according to UID, use -n option to do that.
#sort -n -t: -k3 /etc/passwd
Note: For example with out -n option sort will put 10 before 3 when it find this values, by default it will sort only first numerical char.
Example5: Sort the file and reverse the order
#sort -r filename.txt
Example6: Some times its required to sort the file and display only uniq values.
#sort -u filename
Note: though the values on other field are different this will not consider by -u option.
Example7: I want to sort a file according to my requirement and save it to a different file. Use -o option to save the sorted output to a file.
#sort -o temp.txt filename.txt
You can now mix above options to get your sorting work done.

No comments:

Post a Comment