How to rename files and directories in Linux

Published on Aug. 22, 2023, 12:13 p.m.

Renaming the files and directories is a frequent task .Fortunately, Linux has an effortless way of renaming files and directories.

The mv command is basically used to move the files from one location to the another.But it’s also widely used as a way to rename files as well.

Syntax:

mv [old_name_of_directory] [new_name_of_directory]

First, check the directories present in the current working directory .

ls

Now, we will rename the folder named daa to robot .

mv daa robot

Then, check the list of directories again .

gaurav@ubuntu:~/workspace$ ls
dmta  pc  pmcd  qps  robot  ssda

If you try to change a directory to a name already used by another directory in the desired location, the old name will be deleted and written with the new one.

gaurav@buntu:~/workspace$ mv dmta qps
gaurav@ubuntu:~/workspace$ ls
pc  pmcd  qps  robot  ssda
gaurav@ubuntu:~/workspace$

Using rename Command To Rename Directories

Mv is a very basic command and also has ambiguous behaviour.To overcome these shortcomings we can use the rename command.

Install rename on Ubuntu and Debian :

sudo apt-get install rename

After installing rename, use the code below rename a directory.

Syntax:

sudo rename [perl expression] [directory]

Example:

root@ubuntu:~# ls
DIR1  dir2  dir3  dir4  dir5  pc  snap
root@ubuntu:~# rename 's/dir2/ssh/' dir2
root@ubuntu:~# ls -l
total 28
drwxr-xr-x 2 root root 4096 Sep  9 15:15 DIR1
drwxr-xr-x 2 root root 4096 Sep  9 15:15 dir3
drwxr-xr-x 2 root root 4096 Sep  9 15:15 dir4
drwxr-xr-x 2 root root 4096 Sep  9 15:15 dir5
drwxr-xr-x 2 root root 4096 Sep  9 15:19 pc
drwxr-xr-x 3 root root 4096 Sep  9 14:59 snap
drwxr-xr-x 2 root root 4096 Sep  9 15:15 ssh

Rename Multiple Directories at Once Using rename Command

I’ll change the names of these files using the renaming command to upper case letters.

sudo rename 'y/a-z/A-Z/' [directories_to_rename]

Using renaming to change the names of the highlighted directory.

root@ubuntu:~# sudo rename 'y/a-z/A-Z/' *.sql

In this tutorial, we specifically learnt how to amend the directory names.