Skip to the content.

Regular Expressions & Grep

-

What we’ll cover

-

Grep

grep is used to search for a specified text or pattern within files. ggrep is a version of the command that is compliant to GNU standards that can be used in our Mac evironment.

We’ll be using ggrep with the flag -P (for Perl regex) to demonstrate our pattern matching with Regular Expressions.

to install it on your Mac:

brew install grep

-

Regex basics

-

Basic symbols

-

Dot matching

. - matches any one character

-

Repeated matches

-

Repeated matches (continued)

-

Advanced Matching

-

Boundaries

-

Character classes

-

Predefined character classes

Shortcuts for commonly used character classes

-

Backtracking

-

Lazy quantifiers

AKA Reluctant quantifiers

-

Flags

Remember, flags can be combined.

-

Commands worth knowing: wc

The wc (word count) command is used to find out number of newline count, word count, byte and characters count in a files specified by the file arguments.

syntax:

# wc [options] filenames

The following options can be used to specify its actions:

-

Other commands worth knowing

The results of searches can be sent another command by using the pipe | symbol. Here, we are sending the results of one ggrep search to another ggrep execution:

ggrep "^foo.#bar$" file.txt | ggrep -v "baz"

(same search as grep, but filter out the lines containing “baz”)

The results of searches can also be sent to a file

ggrep -iP -r "[A]\Sl" poetry/ > search_results.txt

-

Resources

-

cute bunny