Regular Expressions In Linux

A regular expression, (also known as regexp or regex) is very useful for to match a string of text such as specific words, groups of words or characters.

 

Now, by themselves, regexps don’t do much. But combined with Linux search tools, they are very powerful. Here we’ll use the grep tool with regexps.

 

Now let’s take a look at an example. Say you wanted to find all the lines in a text file that started with the word “Joe” in a text file called bob.txt. You really can’t do this kind of thing with a typical GUI search tool. But with grep and regexp, it’s easy. Well, easy once you get the hang of it!

 

Our file bob.txt contains six lines:
Bob is a great guy
Unlike his buddy, Joe.
Bob likes to work.
Joe is a real bum.
Joe likes to watch other people work.
Jim is my hero.
James is not.

 

Here’s the grep command:

grep ‘^Joe ‘* bob.txt

Output:
Joe is a real bum.
Joe likes to watch other people work.

Notice how only the lines that start with Joe are printed?

The ‘^Joe’* part is the regular expression.

The ^ means start at the beginning of the line.
“Joe” means search for the word Joe.
The * is a wildcard meaning anything can come after Joe.

What if we wanted to match all lines in which the second letter is “o”?

In this case we need to use the. (period), which tells grep to search for any single character.

grep ‘^.o’ bob.txt

Output:
Bob is a great guy.
Bob likes to work.
Joe is a real bum.
Joe likes to watch other people work.

 

The [] brackets, are used to match a range of characters. For example, we could search for any lines that start with a “J” then any letter between a-m.

grep ‘^J[a-m]’ bob.txt

Output:
Jim is my hero.
James is not.

Now, even though Jim starts with a “J”, it is excluded because the second character is not between a-m.

 

I hope this gets you more familiar using regexps. Please be aware that there are several versions of grep and some use slightly different regexp expressions. If you find a great regexp on the internet and it doesn’t work on your system, it may be because it’s not compatible with your particular version of grep. We’ve only touched the surface here, but I hope this gives some understanding of regexps and a hint at how powerful they can be.

 

Rand’s Adjustable Safety Razor website is a fantastic resource for old-school double-edge razor fans. Check out the Merkur safety razor page for info on Merkur’s adjustable safety razors.

Find More Linux Redhat Articles

This entry was posted in Tutorials and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*
*

Powered by WP Robot

Show Buttons
Hide Buttons