Bash:Bash-Globbing

From Juneday education
Jump to: navigation, search

Introduction

This short chapter will introduce the concept of Globbing (wikipedia).

Globbing is about expressing simple patterns for matching file and directory names. We'll show you by example, so please fire up a terminal and follow the instructions below.

The operators [], [!], ?, * and {}

We will create nine files in your test directory. The files will be empty but created with one single command:

$ touch file_{1..9}.txt   # {} is specific to bash and actually not part of globbing!
$ ls
file_1.txt  file_3.txt  file_5.txt  file_7.txt  file_9.txt
file_2.txt  file_4.txt  file_6.txt  file_8.txt

Now, lets learn about the globbing symbol *. A single * means "any number of any characters". The expression [0-9] means "one character which is a number between 0 and 9".

Let's use a combination of * and [0-9]:

$ ls *_[0-9].txt
#all files that have *_ followed by one digit followed by .txt:
file_1.txt  file_3.txt  file_5.txt  file_7.txt  file_9.txt
file_2.txt  file_4.txt  file_6.txt  file_8.txt

Next, create a new empty file:

$ touch file_99.txt

Let's list all the files which have only one number character after the underscore:

$ ls *_[0-9].txt  #the file_99.txt file will not be listed!
file_1.txt  file_3.txt  file_5.txt  file_7.txt  file_9.txt
file_2.txt  file_4.txt  file_6.txt  file_8.txt

As you see, the new file file_99.txt didn't match the globbing expression *_[0-9].txt, since it had more than one number between the underscore and the .txt part.

Now, let's use a globbing expression which will match file_99.txt but not the other files:

$ ls *_[0-9][0-9].txt
file_99.txt
# The file was listed, because it, and only it,
# had _ followed by two digits followed by .txt
# When we are done playing, remove the newly created text files.

There is one more operator in globbing, we'd like to show you. It is the ? operator which matches "one single character".

$ touch a.txt ab.txt abc.txt
$ ls ?.txt
a.txt

?.txt matches one single character followed by ".txt" so a.txt but not "ab.txt", nor "abc.txt" etc.

Finally, we'd like to show you inverted lists. Let's say we have the files file_1.txt file_3.txt file_5.txt file_7.txt file_9.txt file_2.txt file_4.txt file_6.txt file_8.txt, and we want to match all files in that list, except file_4.txt and file_5.txt.

What we want to express then, is all files beginning with "file_" and a character (but not "4" or "5") followed by ".txt".

This is what it looks like in globbing (works on Unix-like systems): file_[!4-5].txt:

$ ls file_[!4-5].txt
file_1.txt  file_3.txt  file_7.txt  file_9.txt
file_2.txt  file_6.txt  file_8.txt

Links

Further reading

Where to go next

Next chapter is about shell expansion.

« PreviousBook TOCNext »