Basic Grep Searching
Grep is a tool for searching through the contents of files on the command line. It can be very useful for activities like finding records in log files or searching a directory of files for specific content. Anyway, it is a very powerful tool that has many options which can make it quite complex to construct a useful command.
Typically when I use it always takes me a few tries to get the syntax right because I forget how the basic options go. So I figure I would record it here for future reference; so a basic search goes like this:
grep -rni searchterm /path/to/directory/or/file
The basic form of the command is the command followed by options followed by the search term and then where in the file system to look.
The options are as follows:
- r is for recursive, this way if you are trying to search a folder it will search all files in the folder and everything in all sub-folders too.
- n means it will show you what line of the file the the match was found. this can be useful to know if you are looking through files to find and change something.
- i means that the search will be case-insensitive. Which means that it doesn’t care whether or not the match is made up of uppercase or lowercase letters. So if your search term is foo; Foo, FOo and FOO will all be a positive match.
There are many more options but these are the most useful typical options.
The search term cannot have any spaces in it unless you put quotes (or something) around it. You could also use basic regex (i.e. ?+.).
The path is the last argument and it can be a folder or a single file. If you specify a folder it will search the whole folder and all of its sub-folders, you can also use an asterisk to specify a range of files and folders.