How it works...

The previous script uses a for loop to iterate through the names of all files ending with a .jpg or .png extension. The find command performs this search, using the -o option to specify multiple -iname options for case-insensitive matches. The -maxdepth 1 option restricts the search to the current directory, not any subdirectories.

The count variable is initialized to 1 to track the image number. Then the script renames the file using the mv command. The new name of the file is constructed using ${img##*.}, which parses the extension of the filename currently being processed (refer to the Slicing filenames based on extensions recipe in this chapter for an interpretation of ${img##*.}).

let count++ is used to increment the file number for each execution of the loop.

Here are other ways to perform rename operations:

  • Rename *.JPG to *.jpg like this:
        $ rename *.JPG *.jpg
  • Use this to replace spaces in the filenames with the "_" character:
        $ rename 's/ /_/g' *

# 's/ /_/g' is the replacement part in the filename and * is the wildcard for the target files. It can be *.txt or any other wildcard pattern.

  • Use these to convert any filenames from uppercase to lowercase and vice versa:
        $ rename 'y/A-Z/a-z/' *
        $ rename 'y/a-z/A-Z/' *
  • Use this to recursively move all the .mp3 files to a given directory:
        $ find path -type f -name "*.mp3" -exec mv {} target_dir \;
  • Use this to recursively rename all the files by replacing spaces with the _ character:
        $ find path -type f -exec rename 's/ /_/g' {} \;