Searching a text in files from command line

Sometimes we want to search some text which we suppose to be in some location, files or directories. We may use mc (midnight commander) or some other ‘commander’ or just use command line.
So, to search some text, for example, we want to get function (text) which is contained in the current directory among the .java files (we suppose we have some folders there with java source content). So, we type in command line:
ses@ses-laptop:~/tomcat6/webapps/examples/WEB-INF/classes$ grep -rn ‘setContentType(‘ . and got the result like this:

So, here we are finding function ‘setConentType’ (it uses wild card by default), in the current directory (‘.’). As we can see we used flag -n, it means – show numbers where it matched the result, and -r – it means search in subdirectories recursive.
It quite useful, isn’t it ? I have used to use command grep in the way like this: ps | grep tomcat (for example) , but as you can see it is not only one way how you may use it.

Also, you may use ‘man grep’ or ‘info grep’ to get more info about this command (there are a lot of options there), but i just want to mention one more useful one. You may type this one:

grep -rn –files-without-match ‘setContentType(‘ .

and you will get all files that do not contain the pattern (in our case ”setContentType(‘). It’s very useful feature as well right?

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: