Finding words in files… take two!

In the last post we discussed how to find a word in the file /usr/share/dict/words using more.  This being Linux®, there’s always another way to do it.  This way uses the command grep. Jumping right to an example, try this:

Alpha:~ computerlamp$  grep way /usr/share/dict/words

This returns every single word in the file /usr/share/dict/words that contains way.  As in the last post, we’re looking for words that begin with way, not any word that contains way. We can find those words using:

Alpha:~ computerlamp$  grep ^way /usr/share/dict/words

This returns every word that begins with way.  When I tried it, I got 48 words.  How many do you get?

grep is case specific. This means that if you tell it to find way, it won’t find Way or wAy or waY. It matches precisely what you give it. As luck would have it, we don’t have to grep for every possible combination of case. There’s a flag for that. We can use the flag -i to ignore the case. That means, match every possible case when looking for the word way. For example:

Alpha:~ computerlamp$  grep -i ^way /usr/share/dict/words

That finds every possible word that begins with way, no matter what case it has in the file.

How, what happens when you look for a string in a command?  Can I grep grep?

Let’s try it:

Alpha:~ computerlamp$  grep test /usr/bin/grep

I got nothing back.  So it didn’t fail, but it didn’t work.   That’s because the command grep is a binary, which means there’s generally no text in it.

Now let’s try something else!  Suppose we want to find all strings in the file that don’t match our string.   So following our example, we want all strings in /usr/share/dict/words that don’t have the string way in them.  In this case, we do:

Alpha:~ computerlamp$  grep -v way /usr/share/dict/words

If you do this,  you get a lot of results.  An awful lot of results.

 

 

One thought on “Finding words in files… take two!

  1. Pingback: Finding Processes - ComputerLamp

Leave a Reply

Your email address will not be published. Required fields are marked *