In previous article, we saw how to Search in a file with vim. Therein, we opened a file and then looked for a specific search term. With grep, we don’t have to open the file to see if the search term is present inside the file or not. In this article, we move one step further and search in files with grep command-line utility.
grep stands for Global Regular Expression Print. It is used to print all the lines which contains the pattern we are looking for. With grep, we can look for a pattern in ‘n‘ number of files. So, if we want look for a pattern in all the files of a directory then, we can do –
grep <pattern> *
where, * is for all the files in the directory.
In the output, it will show us the file name and the entire line which contains the pattern. Both of these would be separated by a colon. For instance, the output may resemble –
It is worth mentioning here that, grep searches are case-sensitive. In other words, it would treat upper case and lower case letters as different.
Search in files with grep
I. We will start with case-insensitive searches first. Use -i option for case-insensitive searches.
grep -i <search_term> <file_name>
grep -i IP /etc/hosts
It would show all the lines which contain “IP” and “ip” search term (since the search was case-insensitive – therefore, both the search terms gets included).
II. But, for case-sensitive grep –
grep <search_term> <file_name>
Continuing with the above example –
grep IP /etc/hosts
It would show only the exact match of the search term and ignore the lower case part of it.
III. Sometimes, we want to ignore a particular pattern. In those cases, we have to use -v option.
grep -vi <ignored_term> <file_name>
For instance, if we want to ignore IP in /etc/hosts file.
grep -vi IP /etc/hosts
Now, see the difference in output. This time around it ignores all the lines which contain IP, while it displays the rest which don’t contain the term – IP.
IV. Apart from searching in the files, we can also grep the search term from a command output. We do it with the help of pipe ( | ).
<command_instructions> | grep <pattern>
cat /etc/hosts | grep IP
In conclusion, we have discussed how to search in files with grep command-line utility.