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.

Match exactly n occurrences of the preceding regex.
Match at least n occurrences of the preceding regex.
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.


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

Take your Linux skills to the next level!

System Admin Handbook

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

This book approaches system administration in a practical way and is an invaluable reference for both new administrators and experienced professionals. It details best practices for every facet of system administration, including storage management, network design and administration, email, web hosting, scripting, and much more.

$ Check price
74.9974.99Amazon 4.5 logo(142+ reviews)

More Linux & UNIX resources

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