How to Rename Files and Directories in Linux

Renaming files and directories is one of the fundamental operations in the Linux command-line. While renaming a single file is a pretty straightforward task, renaming multiple files and directories can be a little more tricky.

 

In this guide we will go through a number of different ways to rename files in Linux. While the methods we are using here are focused towards Linux, the same commands will work with other popular Unix-like operating systems such as macOS.

 

Rename Files with the MV Command

The mv command stands for move and while its intended function is to move files and directories, it can also be used to just change the name of a file or directory.

MV Syntax

mv [options] source destination

mv takes an optional set of options, a source file and finally a destination. Here are a couple of points to know about the functionality of mv:

  • If the source is a single file and the destination is an existing directory the source file will simply be moved into that directory.
  • You can specify multiple source files, though the destination must be a directory.
  • To rename a file specify a single file and its new name as the destination.

 

Lets rename example.txt to new.txt using mv:

mv example.txt new.txt

 

For a single directory we can use mv in the same way. Let's rename directory1 to directory2:

mv directory1 directory2

 

You can also rename a file/directory and move it to a new destination simultaneously by suppling a path and filename as the destination:

mv example.txt /var/www/skillsugar/new.txt

 

Rename Multiple Files Using Mv

It is only possible to rename one file at a time using the mv command. Though it is possible to run mv within a for loop in Linux to automate the process of renaming many files.

 

The following example shows how to change all files with the .html extension to .php within the current working directory using a for loop:

 

for file in *.html; do 
  mv -- "$file" "${file%.php}.php"
done

 

Rename Files with the Rename Command

rename is a utility that provides advanced functionality for renaming files in Linux VIA the command-line. To install rename use the following instructions:

 

Install on macOS

brew install rename

Install on Ubuntu

sudo apt install rename

Install on CentOS

sudo yum install prename

 

The syntax of rename is the following:

rename [options] perlexpr files

 

As you can see the rename command takes an optional set of options, a Perl expression and the files to be renamed.

rename -n 's/.html/.php/' *.html

In the above example we are getting all .html files using the * (asterisk) regular expression and changing their extensions to .php

 

You will also notice the -n option in the command; this option tells rename to only output the names of the files that are to be renamed. This is useful for checking if your Perl expression is going to behave how you intended it.

 

terminal file