Skip to main content

Working with Basic Regular Expressions

Hands-On Lab

 

Photo of Kenny Armstrong

Kenny Armstrong

Linux Training Architect II in Content

Length

00:30:00

Difficulty

Beginner

Each Linux system administrator needs to have a basic understanding of Regular Expressions, and how to use them. This learning activity will provide you with the chance to practice using some of the more common regular expressions, and utilizing output redirection to create new files.

What are Hands-On Labs?

Hands-On Labs are scenario-based learning environments where learners can practice without consequences. Don't compromise a system or waste money on expensive downloads. Practice real-world skills without the real-world risk, no assembly required.

Working with Basic Regular Expressions

Introduction

Hello there. We've got a few simple tasks we need to perform, just to get the hang of regular expressions. We'll be reading some text files and redirecting some output (output that we'll decide on using regular expressions) to other text files.

Locate HTTP Services

We want to read all of the lines in /etc/services that start with http (but not any that start with httpx) and send them to ~/http-services.txt.

This will get it done for us:

grep ^http[^x] /etc/services > ~/http-services.txt

To check if we have what we want in the new file, run:

cat ~/http-services.txt

Locate LDAP Services

This one is a little trickier. We want to find all of the lines in /etc/services that start with ldap. The fifth character can be any alphanumeric character, but the sixth character can not be an a. We'll dump the output into ~/lpic1-ldap.txt.

grep ^ldap.[^a] /etc/services > ~/lpic1-ldap.txt

To check if we have what we want in the new file, run:

cat ~/lpic1-ldap.txt

Refine the HTTP Results

We want to read the ~/http-services.txt file that we created earlier, and just look at lines that don't end with the word service. This grep command will do it:

grep -v service$ ~/http-services.txt > ~/http-updated.txt

To check if we have what we want in the new file, run:

cat ~/http-updated.txt

Conclusion

We made it through, and now we've got a better handle on using some simple regular expressions to glean pertinent information from text files. Congratulations!