Learning To Use Grep in Linux

Learning To Use Grep in Linux

To find text patterns in files in Linux, you can use grep to do it easily. For instance, you want to find a file which contains the word “spaghetti”, grep will help you to search the file “grep spaghetti joe.txt”.

These text patterns we use to tell grep what to look for are called regular expressions. Regular expressions are a bit daunting at first, but once you get the hang of using them, they can be quite powerful.

The most basic grep command takes two arguments: the regular expression and the name of the file you want to search. Here’s an example grep command which searches for the word “beans” in the text file called joe.txt:

grep beans joe.txt

Here’s the content of the text file joe.txt:

I like spaghetti.
And I like peas.
Give me some beans!

The output of our command, grep beans joe.txt is

Give me some beans!

So grep looks in the text file called joe.txt and then searches for a line containing the word “beans” and prints it out.

Learning To Use Grep in Linux
Learning To Use Grep in Linux

You can also search for two or more words like this:

grep “I like” joe.txt

And the output would be:

I like spaghetti.
And I like peas.

You can use a few different flags with your grep command to change the output. These flags are also called switches. Here are some of the basic switches for grep.

The -c switch will tell grep to count the number of times the word “like” appears in the file.

See also  Linux Mint MATE Desktop Include Compiz Graphics

grep -c like joe.txt

Output: 2.

The -i switch tells grep to perform case insensitive searches. That is, searches where upper and lower case letters are treated as a match. So “Joe” and “joe” would be a match. Without the -i switch they would not.

grep -i Peas joe.txt

Output: And I like peas.

What if you wanted to count all instances of the word “Peas”, with a case insensitive search?

grep -i -c Peas joe.txt

Output: 1

Just put the two switches after the hyphen.

Now, what if you want grep to output all *non matching* lines? Here’s an example that searches for “peas”, then prints out all other lines not containing the word “peas”.

grep -v peas joe.txt

I like spaghetti.
Give me some beans!

Now, for the grand finale! Let’s perform a case insensitive search that counts lines containing all lines that do *not* include the word “spaghetti”.

grep -c -i -v “Spaghetti” joe.txt

Output: 2

I hope this helps you become a little more familiar with the grep tool. Keep practicing! Keep nice and cool in summertime with Carrier ptac units and toasty warm in winter with a ptac heat pump! PTAC air conditioners are easy to install and easy to maintain.