Friday, August 12, 2011

Linux Commands - find and sort


In this post, I want to show you some useful Linux  commands that can be experimented on your terminal.

Find

The find command is used to locate files on a Unix or Linux system.  find will search any set of directories you specify for files that match the supplied search criteria. he syntax looks like this:

find where-to-look criteria what-to-do

If you simply enter find in your terminal, it will display the path names of all files in the current directory and all sub directories. You can give the path of specific directory also.

$ find /home/ajay/web.py-0.36/project/templates/

You can also search for specific type of files.

$ find /home/ajay/web.py-0.36/project/static/ -name \*.gif

The above code will show you the gif files in the specified path. Other files will not be displayed. Try the following code now,

$ find / -mmin -10

It displays the files that are modified less than 10 minutes ago. There are also other interesting uses with the find command. Now lets check another Linux command sort.

Sort

It have the syntax,

sort <flags> <sort fields> <file name>

Sort command can be used in various ways and we can illustrate it using an example. I have a file a.text having following values,

$ cat a.text 
Ajay 23 74
Amala 23 82
Jinesh 22 75
Anoop 21 76
Arun 20 70

If you want to sort this file by the first word of the line, type,

$ sort a.text 
Ajay 23 74
Amala 23 82
Anoop 21 76
Arun 20 70
Jinesh 22 75

If you want to sort in reverse order,

$ sort -r a.text 
Jinesh 22 75
Arun 20 70
Anoop 21 76
Amala 23 82
Ajay 23 74

If you want to save the result into a file, then use,

$ sort -r a.text > b.text

Check b.text,

$ cat b.text 
Jinesh 22 75
Arun 20 70
Anoop 21 76
Amala 23 82
Ajay 23 74

If you want to sort the file by the second field, then use,

$ sort +1 -1 a.text 
Arun 20 70
Anoop 21 76
Jinesh 22 75
Ajay 23 74
Amala 23 82

If we replace +1 by +0, we will get the sorted file by the first field.

$ sort +0 -1 a.text 
Ajay 23 74
Amala 23 82
Anoop 21 76
Arun 20 70
Jinesh 22 75

Suppose we have a data like,

Jinesh,22,75
Arun,20,70
Anoop,21,76
Amala,23,82
Ajay,2374

which is separated by commas, then we can specify the delimiter. Because the field separations should be specified.

$ sort +1 -1 b.text

will not give expected result, since it cannot understand the fields. So specify the delimiter. Here given the results without using delimiter and using the delimiter.

$ sort +1 -1 b.text 
Ajay,23,74
Amala,23,82
Anoop,21,76
Arun,20,70
Jinesh,22,75

$ sort -t, +1 -1 b.text 
Arun,20,70
Anoop,21,76
Jinesh,22,75
Ajay,23,74
Amala,23,82

-tx is the format and we need to replace x by the delimiter. Here it is comma. Any delimiter symbols can be used such as colon, semicolon, hyphen etc.

Thanks

AJAY

No comments:

Post a Comment

Comments with advertisement links will not be published. Thank you.