In the shell, you'll often find yourself working with collections of files. For example, you might have lots of text files, Python scripts, or GIFs.

Right now, I have a collection of many image files in one directory, some of which have .gif extensions and some of which have .png extensions. The former are animated GIFs used for these guides, and the latter are still screenshots saved as PNGs.

That's a lot of files. I've decided I want to put the GIFs in their own folder, but how to move them without typing all of those names?

Well, Bash supports a number of wildcards for working with files, including the basic * and ? just discussed. Let's try the mv command with a wildcard:

[email protected] ~/adafruit_guides $ ls | wc -l
160
[email protected] ~/adafruit_guides $ mkdir ../adafruit_guide_gifs
[email protected] ~/adafruit_guides $ mv *.gif ../adafruit_guide_gifs
[email protected] ~/adafruit_guides $ ls | wc -l
63
[email protected] ~/adafruit_guides $ ls ../adafruit_guide_gifs/ | wc -l
97
[email protected] ~/adafruit_guides $ 

To break this down,

  1. ls | wc -l pipes the result of ls to wc, which is a command for counting words and lines. The -l option tells it to only return the number of lines. This just tells us the number of files in the current directory.
  2. mkdir ../adafruit_guide_gifs makes a new directory one level up from the current working directory (remember that .. is another way of saying "the parent of this directory").
  3. In mv *.gif ../adfaruit_guide_gifs, the wildcard *.gif is expanded by Bash to a list of all the files ending in .gif in the current directory, and then the command is executed like normal.
  4. We use wc -l again to show that we've moved 63 files to adafruit_guide_gifs.

Since filename expansion of this kind (also known as globbing) is built into Bash, it works with any command that takes a list of filenames.

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

This page (Use Wildcards in Bash) was last updated on Mar 16, 2021.

Text editor powered by tinymce.