grep is a very useful terminal command used to search for text within files, the default is to print all lines that contain the given string.
Examples:
grep word file -> print all the lines of the file containing the word.
cat file1 | grep keyword
Unix command | grep keyword
Here are some options:
Incasesensitive -i, search the word is that uppercase to lowercase (or mixture of both)
grep -i rome file -> get as output Rome, but also ROmE and rome
-l list only the names of files that contain the given string, and not the lines
grep -l myclass *. css -> Get the name of all css file containing my class
-r recursive, or search the current path and also in all subdirectories
grep -r “192.168.0.1” / etc / -> look in /etc/ all occurrences of that IP .
-v reverse, or print all lines that do not contain the given string
grep -v “spam” /var/spool/mail -> print all lines that do not contain the string spam
Pipe with other commands
As mentioned grep can be used after other programs to display only a certain portion of the output
See how the disks were seen by the kernel at boot:
dmesg | grep -i “sd”
Show only firefox process among all the process of the system
ps -ef | grep -i firefox
These are some small examples, grep command is very versatile for use in combination with other commands to customize the output, my advice is to do some testing, once known you’ll see in unseperable..
Popular Posts:
- None Found
Just a small correction. The option -L presents the files “that do not contain” the given strain. The lowercase -l actually gives the result indicated in the example.
Thank you Carlos, post fixed.
Hey nice tutorial and excellent blog but the article is in italian although the language flag is set to English. Do you have the article translated? I believe your articles and howtos are awesome and grep is on of the most powerful commands that I know of but I find it very difficult.
Thanks and hope you can update it 😀
Thanks for the comment Rafalgar.
I’ve restored the English version of this post.