Exploring the world of metacharacters in Linux


A metacharacter (wildcard) is a symbol or set of symbols that replaces other characters – they are usually used to work more effectively with files.

In Linux, we encounter 3 classes of wildcards:

? Question mark
A question mark (?) Can replace a single character. For example, b??n can mean any 4-character file name that begins with b and ends with n. The question mark (?) can replace both capital and small letters.

* Asterisk
An asterisk (*) can replace any character or set of characters, even no character – in other words, it can replace a sequence of characters from zero to infinity.

For example, b*n can be any character or character string as long as it begins with b and ends with n.

[ ] Square brackets

Square brackets ([ ]) are used to have any character in a specific set of characters. For example, be[ea]r can mean both beer and bear.

Each pair of square brackets is used for a one-character match. In the example above, it is noted that the second character in the file name can be e or a – and not other.

We can use multiple pairs of square brackets: for example, the filename of [ae][cx]cept can be accept, except, axcept and eccept.

It is also possible to specify a range of values using square brackets. For example, b[b-e]er may be bber, bcer, bder or beer – which means, the small letters from b to h, and no other combinations.

Also, with the help of square brackets, certain characters can be removed: a[!dp]en means single-character matching, except those displayed (less d or p).

Wildcards are implemented in the shell and can be used with certain file manipulation commands. For example, if we give the command ls r??h, the result is accurate and it will display strictly the files that fit our requirements – rash, rath, resh, rich, roch, rukh, rush and ruth – as if we had written it.

The process of using wildcards is known as globbing file, filename expansion, or, more simply, globbing.

Recent Posts