Finding All Your MP3 Files

Problem

You have MP3 audio files scattered all over your filesystem. You’d like to move them all into a single location so that you can organize them and then copy them onto a music player.

Solution

The find utility can locate all of those files and then execute a command to move them where you want. For example:

$ find . -name '*.mp3' -print -exec mv '{}' ~/songs \;

Discussion

The syntax for the find utility is unlike other Unix tools. It doesn’t use options in the typical way, with dash and single-letter collections up front followed by several words of arguments. Rather, the options look like short words, and are ordered in a logical sequence describing the logic of which files are to be found, and what to do with them, if anything, when they are found. These word-like options are often called predicates.

A find command’s first arguments are the directory or directories in which to search. A typical use is simply (.) for the current directory. But you can provide a whole list of directories, or even search the entire filesystem (permissions allowing) by specifying the root of the filesystem (/) as the starting point.

In our example the first option (the -name predicate) specifies the pattern we will search for. Its syntax is like the bash pattern matching syntax, so *.mp3 will match all filenames that end in the characters “.mp3”. Any file that matches this pattern is considered to return true and will thus continue to the next predicate of the command.

Think ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.