How do I batch rename files?

Solution 1:

Open a terminal. Firstly, double check you have the perl rename, by typing man rename. At the bottom, it should say perl v5.18.2 or similar. (I think Ubuntu always ships the perl rename, but other distros ship other versions.)

If it's the correct version, then cd to the directory that contains these files. Then run

 rename 's/^hortstu/hortstu_/' hortstu[!_]*

Explanation

  • This will rename all files that match hortstu[!_]*. This means files that start with hortstu, and do not have _ next.
  • It will then rename them by
    • finding ^hortstu (i.e. hortstu at the beginning of the string)
    • replacing it with hortstu_.
  • N.B. the format for hortstu[!_]* is a bash glob. The format for ^hortstu is a regular expression.

Solution 2:

Or a Bash one liner navigate to the folder with the files and then run this in terminal:

for file in hortsu*;do echo "$file" "${file/_/-}";done;

Basically what this does is for files with the name 'hortsu' followed by any characters '*', echo the name of "$file" and also the name of file with all underscores replaced with dashes. When you feel comfortable with that just replace echo with cp to copy the files to the new name.

A pythonic solution.

Try this in a safe environement, maybe copy one or two files over to a new folder to test how it works.

Save the following code in gedit and give it a name with a file extension of '.py' something like rename_files_in_current_directory.py:

# copy this code into gedit and save it to the directory with the files in it
import os
# for files in the current directory ('.')
for file_names in os.listdir('.'):
    if '_' in file_names:
        # using os.system use cp (copy) to copy file_names to file-names by replacing
        # underscore with dash
        os.system('cp '+file_names+' '+file_names.replace('_','-'))

Make sure python is installed. 'sudo apt-get install python'

Navigate to the folder in terminal with the script and the files and then run:

python the_name_given_to_the_python_script.py

Note:

You can delete the dashes in the above commands and scripts will remove the underscores.

for file in hortsu*;do cp "$file" "${file/_/}";done;

or in the python script change:

file_names.replace('_','-') to file_names.replace('_','')

Solution 3:

For those who prefer GUI applications or just like the ability to preview the result, you might want to install Thunar. It's the main file manager of XFCE; you find it in the repositories.

When you select multiple files in Thunar and rename them (via context menu or F2), you get an elaborate dialog which support all kinds of rename operations. You can solve your problem like so:

enter image description here