Finding Files Irrespective of Case
Problem
Some of your MP3 files end with .MP3 rather than .mp3. How do you find those?
Solution
Use the -iname
predicate (if your version of find supports
it) to run a case-insensitive search, rather than just -name
. For example:
$ find . -follow -iname '*.mp3' -print0 | xargs -i -0 mv '{}' ~/songs
Discussion
Sometimes you care about the case of the filename and sometimes
you don’t. Use the -iname
option when
you don’t care, in situations like this, where .mp3
or .MP3 both indicate that the file is probably an
MP3 file. (We say probably because on Unix-like
systems you can name a file anything that you want. It isn’t forced to
have a particular extension.)
One of the most common places where you’ll see the upper- and lowercase issue is when dealing with Microsoft Windows-compatible filesystems, especially older or “lowest common denominator” filesystems. A digital camera that we use stores its files with filenames like PICT001.JPG, incrementing the number with each picture. If you were to try:
$ find . -name '*.jpg' -print
you wouldn’t find many pictures. In this case you could also try:
$ find . -name '*.[Jj][Pp][Gg]' -print
since that regular expression will match either letter in
brackets, but that isn’t as easy to type, especially if the pattern that
you want to match is much longer. In practice, -iname
is an easier choice. The catch is that
not every version of find supports the -iname
predicate. If your system doesn’t support it, you could try tricky ...
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.