To display the files sorted in ascending order, we use the command ‘sort’. Suppose we have the following file and we want to sort out the data.

linux:~ # more sort.txt
Barrack Obama
George Bush
Bill Clinton
Ronald Reagan
Jimmy Carter
linux:~ #

To sort the file we use the following command:

linux:~ # sort sort.txt
Barrack Obama
Bill Clinton
George Bush
Jimmy Carter
Ronald Reagan
linux:~ #

As you can see, the file has been sorted with respect to the first character per line. What if we want to sort it out with respect to the second names of the presidents? Well, we will use ‘-k 2’ option for this. Check out how it’s done

linux:~ # sort -k 2 sort.txt
George Bush
Jimmy Carter
Bill Clinton
Barrack Obama
Ronald Reagan
linux:~ #
linux:~ #

Note that the sort command won’t change the actual contents of the file rather it will only display it in ascending order. If you want to change the contents of the actual file, use the following command

linux:~ # sort –k 2 sort.txt > sort1.txt

As you must have noticed, we have used a different file ‘sort1.txt’ to save the output. If you use the same file, it will remove the contents of the original file.

Adnan Khurshid

Adnan Khurshid, the author of this article, has been working in a telecommunication sector since 2007. He has worked there as a VAS (Value Added Services) engineer and has excelled remarkably in the field. Working in this field has been his passion and he has always made efforts to keep himself up to date. Find more about him on LinkedIn

More Posts

Tags: ,

3 Comments on How to sort files in Linux

  1. […] command piped after ps. We discussed about sort command before, you might want to have a look at it here. Lets first check the output of ps –aux command as […]

  2. kourtnie says:

    yeah nice

  3. Michael says:

    To sort a file without having to create a new one.

    [host]$ sort file.txt -o file.txt

Leave a Reply