more bash wildcard craziness
Now, what happens if you specify a pattern that doesn't match any file system objects? In the following example, we try to list all the files in /usr/bin that begin with asdf and end with jkl, including potentially the file asdfjkl:
Code Listing 5.5: Another example of the * glob |
$ ls -d /usr/bin/asdf*jkl ls: /usr/bin/asdf*jkl: No such file or directory |
Here's what happened. Normally, when we specify a pattern, that pattern matches one or more files on the underlying file system, and bash replaces the pattern with a space-separated list of all matching objects. However, when the pattern doesn't produce any matches, bash leaves the argument, wild cards and all, as-is. So, then ls can't find the file /usr/bin/asdf*jkl and it gives us an error. The operative rule here is that glob patterns are expanded only if they match objects in the file system. Otherwise they remain as is and are passed literally to the program you're calling.
Wild card syntax: []
This wild card is like a ?, but it allows more specificity. To use this wild card, place any characters you'd like to match inside the []. The resultant expression will match a single occurrence of any of these characters. You can also use - to specify a range, and even combine ranges. Examples:
myfile[12] will match myfile1 and myfile2. The wild card will be expanded as long as at least one of these files exists in the current directory.
[Cc]hange[Ll]og will match Changelog, ChangeLog, changeLog, and changelog. As you can see, using bracket wild cards can be useful for matching variations in capitalization.
ls /etc/[0-9]* will list all files in /etc that begin with a number.
ls /tmp/[A-Za-z]* will list all files in /tmp that begin with an upper or lower-case letter.
The [!] construct is similar to the [] construct, except rather than matching any characters inside the brackets, it'll match any character, as long as it is not listed between the [! and ]. Example:
rm myfile[!9] will remove all files named myfile plus a single character, except for myfile9
? matches any single character. Examples:
- myfile? matches any file whose name consists of myfile followed by a single character
- /tmp/notes?txt would match both /tmp/notes.txt and /tmp/notes_txt, if they exist
0 Comments:
Post a Comment
<< Home