Using grep to search inside files Print

  • 42

One very important tool that Unix provides is the grep command, which processes files line by line and prints out any matching the pattern you have set for it.

Syntax
grep [OPTIONS] PATTERN [FILE...]
Let's say you want to find where file.html is containg the word 'mywebsite.com' you would run the command (from the folder it is in)
grep "mywebsite.com" file.html
If grep finds it, it will output the entire line it is in, making it easier and faster to analyze your files.

To highlight the phrase with a color, you can use the --color option.
To view the line it was found at, you would need to use the -n option.
To do a case insensite server, -i would need to be used.
grep -i -n --color "mywebsite.com" file.html
To use a file wildcard and search all files sharing something in common (like extension, for example), you can use the '*'
grep -i -n --color "mywebsite.com" *.html
This would output any line in any html file in that folder containing mywebsite.com

If you want to do it recursively and search all subdirectories, you would need to add the -r option.
grep -r "mywebsite.com" *.html
Adding -c would give you the number of times the pattern was found, while -l would print the files with matches.

Was this answer helpful?

« Back