next up previous
Next: Searching for People Up: Introduction to the Linux Previous: Pipes and Redirection

Searching for Stuff

Sometimes we want to find a particular file. For example, I installed the Intel Fortran compiler ifort, but it's not on the PATH so the shell cannot find it.

[phasnip@mijpnb1 ~]$ find /usr -name ifort
/usr/local/intel/compiler81/bin/ifort

The first argument tells find where to start looking, and it will search all subdirectories. The -name option will take wildcards, but you need to put them inside quotation marks or the shell will expand them first. Another useful option to find is -exec which will run a command every time a file is found.

We might also want to search a file to see whether it contains certain things. The grep command is perfect for this.

[phasnip@mijpnb1 Linux]$ grep 'Bourne' linux.tex
shell is one of the original shells, and is called the Bourne shell
later). The Bourne shell was reworked and gave rise to the second
shell, called the \texttt{bash} shell, which stands for \emph{Bourne

We might want to know which lines these are

[phasnip@mijpnb1 Linux]$ grep -n 'Bourne' linux.tex
849:shell is one of the original shells, and is called the Bourne shell
852:later). The Bourne shell was reworked and gave rise to the second
853:shell, called the \texttt{bash} shell, which stands for \emph{Bourne

We might also give grep a list of files to search, so it might be handy to know which files the matching lines are from

[phasnip@mijpnb1 Linux]$ grep -H 'Bourne' linux.tex
linux.tex:shell is one of the original shells, and is called the Bourne shell
linux.tex:later). The Bourne shell was reworked and gave rise to the second
linux.tex:shell, called the \texttt{bash} shell, which stands for \emph{Bourne

The most useful thing about grep is that it will search for patterns, called regular expressions. These are like wildcards, but even more flexible.

[phasnip@mijpnb1 Linux]$ grep -n 'Bourne\|bashrc' linux.tex
849:shell is one of the original shells, and is called the Bourne shell
852:later). The Bourne shell was reworked and gave rise to the second
853:shell, called the \texttt{bash} shell, which stands for \emph{Bourne
863:\texttt{.bashrc} and \texttt{.cshrc} respectively, and if things like

The `$\backslash$|' means OR. * means the preceding item may be present, $\backslash$+ means it must be present and $\backslash\{3\backslash\}$ means it must be present 3 times on the line; you can use $\backslash\{3,\backslash\}$ to mean `at least 3' or $\backslash\{3,6\backslash\}$ to mean `3 to 6 times'. Finally the full-stop character means `any character'; if you actually want a full-stop you should use `$\backslash$.'. Use grep -v to return lines that do not match the expression.


next up previous
Next: Searching for People Up: Introduction to the Linux Previous: Pipes and Redirection
Phil Hasnip 2007-08-23