Home > Articles

Wildcards: Operations on Multiple Files

  • Print
  • + Share This
Wildcards allow you to perform an operation on my different files. Jon Lasser shows you how to make good use of these timesaving options.
From the author of

From the author of

Often, it's nice to perform operations on more than one file at a time, especially when those files share parts of their name. Wildcards give us a way to do this. Let's say a user, Elvis, wants to find all of his text files. Wouldn't it be nice for him to see only the files whose names end in .txt? This being Unix, he can use wildcards to do this:

 [ elvis@frogbog elvis]$ ls *.txt
tao.txt things.txt

That asterisk (*) is a wildcard. As in a good old-fashioned game of poker, a wildcard is something that matches anything. If twos are wild, a two can stand in for anything; just so, an asterisk stands in for anything.1 Also as in a poker hand, you can have any number of wildcards: *i* would match Mail, ThisFile, things.txt, and thisfile. It wouldn't match Desktop, README, or tao.txt.

Unlike in a poker hand, an asterisk can stand for any number of things at once: The asterisk in *.txt replaces tao in one instance and things in another. Unix uses a question mark to stand in for any single character: ?his?ile would match both ThisFile and thisfile, but it wouldn't match ThisIsntAFile. Also unlike poker, * can match nothing at all: This* would not only match ThisFile and ThisOtherFile, but also This. A question mark, by contrast, requires that something be present in the space reserved by that wildcard.

Unix has one last commonly used wildcard: Square brackets can be replaced only by whatever characters are within those brackets. [Tt]his[Ff]ile would match only ThisFile and thisfile. (It would also match thisFile and Thisfile, if those files existed in this directory.) One additional complication is that two characters separated by a hyphen can be replaced by any character in that range of ASCII characters. This[A-Z]ile would match ThisFile, ThisMile, ThisBile, and 23 others.

For the sake of intellectual uniformity, consider a range of characters separated by a hyphen as a single character. If you can do this, it's clear that [A-Za-z] matches all uppercase and lowercase letters and that [0-9A-Za-z] matches all letters and numbers.2 This[0-9A-Za-z]ile would match This0ile, This9ile, ThisFile, Thisqile, and anything else with a single letter or number in place of [0-9A-Za-z].

About this Article

This article is excerpted from Think UNIX by Jon Lasser (2000, Que, ISBN 078972376X).

  • + Share This
  • 🔖 Save To Your Account