Wednesday 19 February 2014

What is grep and How do you use it?

That's my random thought today. Given the success I had last week with find and xargs I am inspired to understand the most common unix utility I hear about. The mighty grep.

What is grep?

The technical answer is ok but leaves you guessing. Gnu says
grep prints lines that contain a match for a pattern.
in their grep section

A better definition comes from HowTo: Use grep Command In Linux / UNIX – Examples
The grep command is used to search text or searches the given file for lines containing a match to the given strings or words.

How do you use it?

HowTo: Use grep Command In Linux / UNIX – Examples provides some nice straightforward examples. Though I couldn't get the search working in a folder, just on a file.
grep php /mod/quiz 
returned no such file or directory. It will be user error but it's what the tutorials show.

Though I am using GIT bash on windows 7 MINGW32. That could be the problem.

Turns out I need to prefix the command with GIT e.g.
git grep php mod/quiz

this worked fine but returns too much. So I then tried a search with a smaller file base
git grep link question/type/calculated/lang 
This returned a lot less. I also had to remember to type :q to quit the command in git bash. Note that I don't prefix the path with / this returns and error. ./ works but isn't needed. 

Atleast now I know the basics. I'll find a use for it soon I expect :-)



No comments: