This section describes three commands for searching for files/directories. For additional information about these commands, log onto any COM S Linux/UNIX machine and type man command:
Files in a Directory Hierarchy
This section describes two commands to search for files in specific directories - one for Unix and Linux, and the other specifically for Linux.
Generic Unix Command
The find command searches for files in specific directories. The basic syntax for find is as follows: find path expression.
the path argument is the starting directory from which find will search. The expression argument describes the type of file to find. Here are some examples:
Command | Effect |
---|---|
find /dir -name code.c | Finds all files in the /dir directory named code.c |
find ~ -name myfile | Finds all files in your home directory (~) named myfile. |
find mydir -type d | Finds all directories (denoted by -type d) in the mydir directory. |
You can also use wild cards to search for filenames containing a certain pattern:
Command | Effect |
---|---|
find ~ -name "*homework*" | Finds all files in your home directory with a name containing the phrase "homework". |
There are many more options for find; consult the manual page for more information.
Linux Alternative
Under Linux, the locate command is similar to the find command. Here is an example:
UNIX> locate xpdf
/usr/share/doc/xpdf-0.92
/usr/share/doc/xpdf-0.92/CHANGES
/usr/share/doc/xpdf-0.92/README
/usr/share/man/man1/xpdf.1.gz
/usr/bin/xpdf-handle-url
/usr/bin/xpdf
/etc/X11/applnk/Graphics/xpdf.desktop
/etc/current/db_current/headers/xpdf-0.92-5.i386.hrd.gz
By default, locate finds any files containing the given search string, whereas wind cards must be used with find (e.g. find *xpdf*).
Files in the Command Path
The which command is similar to the find command, except which only searches for binaries that are located in your shell's command path. The which command is useful for determining which version of an executable you are using. Here is an example:
UNIX> echo $PATH
/usr/local/bin:/usr/local/gnu/bin:/usr/bin:/sbin:/bin
UNIX> ls -la /usr/local/gnu/bin/ls /usr/bin/ls
-r-xr-xr-x 1 root bin 18844 Jan 5 2015 /usr/bin/ls
lrwxrwxrwx 1 root root 25 Jan 5 2015 /usr/local/gnu/bin/ls
UNIX> which ls
/usr/local/gnu/bin/ls
- The echo command displays the shell's command path.
- The second command shows that there are two binaries named ls - one in /usr/bin and the other in /usr/local/gnu/bin. (Note that both of these directories are in the command path.)
- The which command chows that the ls command corresponds to /usr/local/gnu/bin/ls, because /usr/local/gnu/bin is listed before /usr/bin in the command path. Therefore, when ls is typed the /usr/local/gnu/bin/ls is used.