How to Rename File and Directory in Linux?

To rename a file there are other commands also like 'mv'. But 'rename' command is slightly advanced then others. This command will be rarely used and it works differently on different distros of linux. We'll work on Debian/Ubuntu examples.

Generally, renaming is not a big task, but when you want to rename a large group of files at once then it will be difficult to rename it with 'mv' command. In these cases, it is adviced to use 'rename' command. It can convert upper case files to lower case files and vice versa and cn overwrite files using perl expressions. This command is a part of perl script.

Linux File System Introduction

The Linux file system provides the support system of the operating system, giving an organized and structured platform to store and retrieve directories and files. It is necessary to have a common knowledge of the hierarchy of the Linux file system. The file system is maintained in a tree-like structure along with the ("/") root directory serving as the beginning point. Several directories and their subdirectories branch out through the root directory, constructing the whole file system.

In Linux, all directories can include files and other directories, constructing a hierarchical structure. The hierarchical structure permits easy management and organization of directories and files. Knowing the file system hierarchy aids users in managing their way via Linux directories and efficiently locating directories and files. It is important to specify the accurate path to run commands and access the target files when operating with the command line.

In Linux, all files are recognized by their path, which describes their location inside the file system. The path of a file includes the directory hierarchy heading to the file, pursued by its name. For instance, the /home/user/documents/text1.txt path shows that the text1.txt is placed inside the directory of the document, which is in the user directory.

Basic syntax:

This ('s/old-name/new-name/') is the PCRE (perl compatible regular expression) which denotes files to rename and how.

Let's see an example of basic rename command:

In the example below we have converted all the files ending with '.txt' into files ending with '.pdf'.

linux-file-rename-command

In another example, we have converted file into document for all files ending with .pdf

linux-file-rename-command

rename option:

rename has some optional arguments but a mandatory perl expression that comes with every opption and guides it how to work.

OptionFunction
rename -nCheck changes before running the command.
rename -vPrint the output.
rename (a-z)(A-Z)/ (A-Z)(a-z)Convert into upper case/lower case.
rename -fForcefully over write existing files.

Renaming Files using the mv Command

mv is a command of Unix that moves one or multiple directories or files from one position to another. If filenames are on a similar filesystem, it provides a general file rename. The content of the file is copied to the fresh location, and the previous file is deleted. Using the mv command needs the user to contain write permission for directories the file would move between. It is due to the mv command modifying both directory's content (the target and the source) involved in the moving process. When using mv on files positioned on a similar filesystem, the timestamp of the file is not updated.

The mv, ln, and cp commands are implemented as one program using hard-linked binaries on UNIX implementations copied from AT&T UNIX. The behaviour is chosen from the argv[0] path name. It is a basic method by which closely associated commands that have been bundled as a unit permit the user to describe the specific course of the desired action.

Options of the mv Command

Most mv versions support:

  • -i: It specifies an interactive process and specifies a prompt on standard error before going to move a file that will overwrite an old file. The move is initiated if the response through the standard input starts with the 'Y' or 'y' character.
  • -f: It stands for force. In this option, force can overwrite the destination.
    The above options are an element of the X/Open Portability Guidelines, later the SUS and POSIX basis. Every POSIX-compliant implementation of mv must support the same.

The syntax of mv is mentioned below:

  • The destination can be one directory or file, and the source can be one or multiple directories or files.
  • The destination should be a directory if we specify two or more files as the source. In this situation, the source files are carried to the target directory.
  • The destination target is an old directory; if we specify one file as the source, then the file is carried to the specified directory.
  • We need to specify one file as the source and one file as a destination target to rename any file.

For instance, to rename the myfile1.txt file as myfile2.txt, we would execute the below command:

Rename multiple files using the mv command

The command can only rename one file at once, but it can be utilized in conjunction with many commands like find or in Bash while or for loops for renaming multiple files.

The below example displays how to apply Bash for loop for renaming every file in our current directory by modifying their extensions:

Let's explain the code step-by-step:

  • The initial line establishes a for loop and repeats from a list of every file edging with the .html extension.
  • The second line uses on all list items and carries the file to a fresh one substituting .php and .html. The ${f%>html}.php part is utilizing the shell parameter expansion to delete the .html part through the filename.
  • done represents the completion of the loop segment.

How to do batch renaming using wildcards?

Wildcards are strong symbols that show character patterns. They enable us to rename two or more files that are specific criteria-based. For example, the wildcard ("*") matches an order of characters. We can efficiently implement batch renaming tasks by merging the mv command and wildcards.

How to rename files with particular criteria?

Linux facilitates many options to rename files on particular criteria-based like file size, permissions, or modification date. The command, i.e., find, permits us to find files that match certain conditions and accordingly rename them.

How to rename files placed in subdirectories?

In subdirectories, renaming files is the same as renaming files within the current directory. We can find files in particular directories and implement renaming tasks.

How to undo file renaming?

We might sometimes be mistaken at the time of renaming files, or we may be required to turn back the modifications for other reasons. It is important to have a record or backup of the actual file names. Simply, we can send the files back to the actual names with the help of the mv command if we have a backup. If available, we might need the file recovery tools or depend on version control systems if we do not have any backup.

Rename command

Two rename command versions are available with different syntaxes. If we don't have it installed on our system, we can install it easily with the package manager of our distribution:

  • Installing rename on Debian and Ubuntu
  • Installing rename on Fedora and CentOS
  • Installing rename on Arch Linux

The following are some more basic examples of how to implement the rename command:

  • Substitute spaces in filenames using underscores:
  • Change filenames into lowercase
  • Change filenames into uppercase

Moving versus removing and copying

Moving files in a similar file system are basically implemented differently as compared to copying the file and deleting the original. A new link is included in the new directory, and the actual one is removed on platforms that don't provide support for the rename syscall. The file data is not accessed. Every POSIX-conformant system operates the rename call.

An original move is dramatically faster as compared to the copy-and-move process. The i-number of the file doesn't change. No permission is needed for reading the file being carried insofar as it's only cataloguing data that's being modified as an outcome of the "move". Since the target and source directories are being changed, entries are being established in the target directory and removed from inside the source directory.

In both directories, "write" permission is needed to finish the move. Carrying files from a single file system to another may entirely fail or may be performed automatically as an atomic copy-and-delete function. The original details are reliant on the implementation.

Advanced methods for file renaming

Linux provides advanced methods for file renaming, giving even more customization and flexibility options. These methods are discussed as follows:

  • Regular expression usage

Regular expressions are strong patterns that permit us to match and employ text. Especially, they are helpful if dealing with complicated renaming operations. Many tools, including SED or Rename, support regular expressions, allowing us to implement complex file-renaming tasks.

  • Using bash scripts

Using bash scripts automates the repetitive and complex renaming task process. We can build custom renaming scripts customized according to our requirements by merging scripting constructs and Linux commands.


 
 

Latest Courses