Sunday, August 8, 2010

Finding Files using text command on Linux

Added: Well, for a general search, "Search for files..." applet works like a charm, moreover it's super fast.


As I use more a text command, I clearly feel that it's faster than using GUI. For example, to find files, with Nautilus (it's like explorer on Windows or finder on Mac), not only it takes a lot of time, but it won't also show me full path that I need.

With 'find' command on Terminal, there's no such a hassle any more, and needless to say, it's much more powerful.


The Unix command "find" is quite powerful, and if you know how to use it you can find pretty well anything. The basic syntax is "find ". Options include criteria for your search, actions to take on files found, etc. I'll give you a couple of examples then point you to the man page for detailed usage and more interesting examples.
You want to find every file in ~/mydir and all its subdirectories, recursively, with a file extension of .htm (or .HTM or .Htm...) and delete it. I've seen a lot of attempts like rm -rf ~/mydir/*.htm which really don't come close. The correct solution is
find ~/mydir -iname '*.htm' -exec rm {} \;

"-iname" says that you want to do a case-insensitive search on the filename. '*.htm' is in single quotes to prevent bash from expanding the *, which will produce unexpected results. The rest of the command says to remove any file matching the query. The "{}" will be replaced by the filename (with path) returned by the search, and "\;" will separate one rm command from the next. Nearly every -exec option should be terminated with a "\;".
Now you want to fix permissions. For some reason, there seem to be directories in your home directory that you don't have permission to enter. You know that the operative bit for directories is the execute bit. You know that "chmod -R +x ~" will add the execute bit to every file and directory in ~ (or $HOME), but you only want to operate on directories - BritneySpearsOopsIDidItAgain.avi doesn't need to be executable. This is solved with:
find ~ -type d -exec chmod +x {} \;

where "-type d" of course means directories.
Finally, you want to make a playlist out of all the mp3 and ogg files in your home directory.
find ~ -type f \( -iname '*.mp3' -o -iname '*.ogg' \) > mynewplaylist.m3u

We group the -iname parameters in parentheses and separate them with -o (the "OR" operator) to say that any match must be a file, AND it must be named .mp3 OR .ogg (case-insensitive) to be returned. We redirect the output to a new file called mynewplaylist.m3u, and presto! We have a playlist.


No comments:

Post a Comment