Knowledge Base

Browse our knowledge base for free solutions to common problems

Mass Rename Files Inside Linux / Mac Directory Using Loop

Created On: 14 September 2022
Written by: Ben

First change directory to the one containing the files you wish to bulk rename:

cd /Users/tony/Downloads/Mexico/

Example of files inside of a directory:

tony@Tonys-MacBook-Air Mexico % ls -1
122 - Mexico - 45674856477658.jpg
123 - Mexico - 75934757979557.jpg
124 - Mexico - 75385739579753.jpg
125 - Mexico - 39579375938789.jpg
126 - Mexico - 73473957397593.jpg
127 - Mexico - 43749375937998.jpg
128 - Mexico - 49374937593999.jpg
129 - Mexico - 94375973583958.jpg

We are looking to remove everything but the unique string and the file extension at the end.

For example "125 - Mexico - 39579375938789.jpg" would turn into "39579375938789.jpg".

Lets try return a list of our files with a find command (from inside the directory with the files):

find . -type f -name '*.jpg'

The list appears correctly now pipe into while loop with:

find . -type f -name '*.jpg' | while read FILE ; do
newfile="$(echo ${FILE} | sed 's/^[^-]* - //' | sed 's/^[^-]* - //')" ;
mv "${FILE}" "${newfile}" ;
done

After the above is run all the files will be renamed to my desired format. This is particularly useful if there are 100's of files.

Explanation:

  • find = Look for something on Linux
    • . = Look inside current directory
    • -type f = Look just for files and ignore directories
    • -name '*.jpg' = Look for files matching wildcard *.jpg
  • FILE = Self declared variable. Could be anything you wish but is always equal to the command previous to it in the example above.
  • sed 's/^[^-]* - //' = Removes anything before a "-" this helps me get my desired output name inside of created variable newfile. There are two dashes thats why I run it twice.

Notes:

  • Depending on your original files naming convention you may need to change the sed argument applied to the newfile variable to something that gives you the desired output name.
ICTU LTD is a company registered England and Wales (Company No. 09344913) 15 Queen Square, Leeds, West Yorkshire, England, LS2 8AJ
Copyright © 2024 ICTU LTD, All Rights Reserved.
exit