Wednesday, March 2, 2011

That's how you can search for files in linux

1- GUI way : You can use your file manager for that. For me I use nautilus so you can go to the toplevel directory you want to start searching from and hit Ctrl + F keys to enter the file name and press enter (That's quite simple).

2- Command line way : If you prefer doing search from command line like I do then open your terminal and search as following:

To find a file in the current directory you can use this command

find -name 'filename'

To find a file in another location, specify the location

find /etc -name 'php.ini' 2> /dev/null

This will search /etc and its subdirectories for the file php.ini. The reason why I am using 2> /dev/null here is that because I am not doing that as a superuser, I can't search in some locations and I get a lot of permission denied errors. I redirect the errors to nothing ( The black hole ! ) /dev/null because I don't care for them now. If you want you can redirect the errors to a file 2> ~/error.log or you can remove this part to display the errors. The command in this case will be

find /etc -name 'php.ini'

Normally the command doesn't follow symbolic links. So if you want to include symbolic links in your search you have to add -follow to the command

find /var/www -name 'index.php' -follow

If I have a symbolic link to a website in my home directory for example. It will be included in the search.

You still can use patterns to search like

find /var/www -name 'index.*'

This will search for index.html, index.php, index.css, index.supercalifragilisticexpialidocious in directory /var/www

Another thing you can search files by size

find -size +100k
find -size -100k
find -size 100M -name '*.tar.gz'

The first command will search for files greater than 100 kilobytes in size, the second command will search for files less than 100 kb in size and the third command will search for files 100 megabytes in size that end with .tar.gz

Another thing you can have different formatting for the output including more information by adding -ls to the command

find /var/www -name 'index.php' -ls

There are other tools to find files and I will discuss them later ( When I understand how they work !)

No comments:

Post a Comment