Grep

Grep is one of those tools that every GNU/Linux user should have at least a rudimentary understanding of. You will get by without it of course, but it can speed up things quite a bit.

Just today a friend and former classmate had a problem: In a large C++ code base, find the one file printing a specific error message. Opening every file and manually checking them: not feasible and surely not cost-effective.

He asked me for any insight in searching, and from the ole’ toolbox I brought grep. Now I will readily admit, I am no superuser, or guru or anything of the sort. My grep skills are not what they probably should be, so my first attempts was rather unsuccessful.

Framing the problem even more, the .cpp files where spread over a number of directories, and in the project root directory there where no files, only directories.

Since I mostly program in Python those where the files I had available to test my grep commands on:

$ grep 'import' *.py

I was greeted with an error, *.py no such file or directory. But the syntax was right, right? Went into a sub directory containing python files, ran the same command again, and was rewarded with a list of files.

Ok, so the problem wasn’t the syntax, it was targeting. What about

$ grep -R 'import' *.py

Again with the error message… ok, quick check in the man-page, yes, -R -r or –recursive all works, great, next try:

$ grep -r 'import' ./*.py

That error message is getting tedious… what about

$ grep -r 'import' ./

Now we are rolling, but it is chewing on things I have no interest in listing… like Vim’s .swp files etc. How do we fix that? Enter the man-page again, aha –include

$ grep -r --include '*.py' 'import' ./

Very nice, recursive search throughout all sub directories for files ending with .py containing the string ‘import’. Now to help him out a little more, let’s add -n also, so that he will see on what line the error message is printed.

$ grep -r -n --include '*.py' 'import' ./

And there you have it. Just one of the various uses of grep.

Tags: ,

Comments are closed.