The people who originally wrote Unix and a lot of the software that runs on it were fond of pattern matching.

You can see this in shells like Bash, in tools like sed (a stream editor used for transforming text) and grep (a finder of text), and in many of the programming languages that emerged in the 80s and 90s.

Pattern matching is an idea that covers a lot of specific tools. For our purposes, it usually means finding a pattern of characters in lines of text, inside files, or in the names of files themselves.

This is usually done by writing patterns in a little language which describes the text to be matched. Here's a really simple version of one of those:

We'll say that *, often said aloud as "star", means "0 or more of any character", and ? means "1 of any character". Any other characters in the pattern will be treated as literal characters, which means they represent themselves and we're literally looking for that character. A b will mean that we want to match on a b.

Consider the pattern R*. It'll match any string of characters that starts with an R, like Ralph or Rob.

How about the pattern R*b? Well, we know Ralph fits some of the criteria. It starts with R, followed by some number of characters, but is there a b at the end?

Not so much. How about for Rob?

Characters like these are often called wildcards, because they're like cards that can stand in for any other card in games like poker.

This guide was first published on Feb 24, 2015. It was last updated on Feb 24, 2015.

This page (Use Pattern Matching) was last updated on Apr 10, 2021.

Text editor powered by tinymce.