How to find files in Linux with grep: 10 examples (free PDF)
The grep command is a handy, reliable tool for searching for files or information. This tutorial illustrates 10 ways to take advantage of its power and flexibility.
From the tutorial:
Windows search is not without certain charms, but when I need to find files or their contents, or search for specific system information, the grep command in Linux never ceases to amaze me with its power and versatility.
There are multiple versions of grep: plain regular grep, egrep (extended grep), and fgrep (fixed prep). The latter two have different methods for working with characters and search strings. I’ll focus on regular grep for the purposes of this article, which is intended as a beginning tutorial for this handy and reliable command.
The syntax of grep is as follows:
grep [options] pattern [files]
The options and patterns you can use with grep are varied and diverse. Here are 10 examples to help sharpen your skills.
1. Search a file for a specific word
This is really one of the most elementary uses for grep. Let’s say I want to inspect the contents of the /var/log/secure log for any instances of a failure. I would type:
grep failure /var/log/secure
This is an example of what grep might then return:
Apr 4 06:45:29 smatteso-vm1 sshd[14836]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost= qualys-corp.testdomain.com user=8boa5lv2rn8pso8
Apr 4 06:45:31 smatteso-vm1 sshd[14844]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost= qualys-corp.testdomain.com user=13hr26mnm8wo4k
Add the -i switch (e.g., grep -i) to conduct a case-insensitive search. In the example above this would return the lowercase failure, uppercase FAILURE, or any combination thereof, such as Failure.