One of the most useful features of operating from a linux terminal is being able to easily perform functions like grep, which searches a group of files for a matching string. It can return lines with the matching expression, lines without the matching expression, the number of lines matched, and more. This will serve as a basic tutorial and should cover most usage models; grep is an extremely powerful tool. Consult the grep manual for a much more detailed description.
The basic syntax and an example of a grep command line is shown below. Note that grep is case sensitive unless otherwise specified so this particular search will only yield resuls with the exact match. Also, grep will not search inside directories unless the recursive flag is passed in (see below).
grep "search pattern" filename grep "Hello world!" textFiles/*
In the example above, grep would have searched all files in the textFiles directory and returned any lines which contain the substring "Hello world!". Below are some of the most useful switches which can be used with grep, followed by some basic examples.
| -i | case insensitive search |
| -c | returns only the number of lines which match the search |
| -v | returns lines which do not match |
| -r | recursive search (otherwise grep will not search inside directories) |
| -P | Interpret the search pattern as a Perl regular expression |
Below are a few examples with a brief explanation of what each line is doing.
1 2 3 4 5 6 7 8 |
## grep for all directories and files inside the current directory grep "my string" * -r ## grep for all files which do not contain 'and', ignoring case grep "and" * -i -v ## count the number of lines which contain 'PASS' in a results file grep "PASS" results.txt -c |
Hopefully this tutorial proves useful as an early dive into grep. Again, consult the grep manual for additional switches which may be relavent to your usage!





