05. Matching multiple characters

With an Asterisk

The asterisk (*) allows you to match zero or a multiple number of the preceding character.

$ ls /usr/bin | grep 'bc*t'
btmmdiagnose ibtool libtool pfbtops

In this example, we are matching commands within our bin folder that have a b, any number of c's (including none), then a t.

Although convenient, the asterisk may be too powerful for your purposes. To have more control over the number of repeating elements, we can use braces.

Using Braces to get more specific

With braces ({...}), we are able to better control how many times an element occurs. In BRE, remember that we must escape the brace characters with a backslash.

\{n\}
Match exactly n occurrences of the preceding regex.
\{n,\}
Match at least n occurrences of the preceding regex.
\{n,m\}
Match between n and m occurrences of the preceding regex.
$ ls /usr/bin | grep '[[:alpha:]]{2}'
perlthanks5.16 perlthanks5.18 piconv5.16 piconv5.18 pl2pm5.16 pl2pm5.18 pod2html5.16 pod2html5.18 pod2latex5.16 pod2latex5.18 pod2man5.16 pod2man5.18 pod2readme5.16 pod2readme5.18

The above code would search for lines of text that have a two digit number.

RE_DUP_MAX

Note that the values for n and m must be between 0 and RE_DUP_MAX. This variable signifies the largest number of repetitions you are allowed in regular expressions.

To check your system's setting for this value, use the command getconf.

$ getconf RE_DUP_MAX
255

Aching back from coding all day?

Inversion Therapy Table

Aching back from coding all day? Try Back Problems

Stretch out your back and relieve your back muscles with inversion therapy. This device counteracts the forces of gravity on the body by decompressing and elongating the spine. By using this product just ten minutes a day, you can be well on your way to improved circulation and posture while relieving muscle aches, back pain and stress.

$$ Check price
119.98119.98Amazon 4.5 logo(1,700+ reviews)

More Back Problems resources

Take your Linux skills to the next level!

Command Line Kung Fu

Take your Linux skills to the next level! Try Linux & UNIX

Command Line Kung Fu is packed with dozens of tips and practical real-world examples. You won't find theoretical examples in this book. The examples demonstrate how to solve actual problems. The tactics are easy to find, too. Each chapter covers a specific topic and groups related tips and examples together.

$ Check price
14.9914.99Amazon 4.5 logo(27+ reviews)

More Linux & UNIX resources

Ad