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:
pi@raspberrypi ~/adafruit_guides $ ls | wc -l 160 pi@raspberrypi ~/adafruit_guides $ mkdir ../adafruit_guide_gifs pi@raspberrypi ~/adafruit_guides $ mv *.gif ../adafruit_guide_gifs pi@raspberrypi ~/adafruit_guides $ ls | wc -l 63 pi@raspberrypi ~/adafruit_guides $ ls ../adafruit_guide_gifs/ | wc -l 97 pi@raspberrypi ~/adafruit_guides $
To break this down,
-
ls | wc -l
pipes the result ofls
towc
, 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. -
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"). - 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. - We use
wc -l
again to show that we've moved 63 files toadafruit_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.
Page last edited February 20, 2015
Text editor powered by tinymce.