Brief: This article guide demonstrates the use of several Linux commands to successfully query the existence of a file or several files before renaming them.
Linux offers multiple terminal command solutions for renaming files regardless of the different paths or locations associated with the targeted files. Renaming a single file is easy but what happens when you have multiple files that should be instantaneously renamed?
This article guide provides an answer to this question.
1. Renaming Files via mv Command
The mv command is inbuilt into all major Linux distributions. The standard approach of renaming a single file via the mv command is represented with the following syntax:
$ mv [OPTIONS] [current/file/name] [new/file/name]
Consider the following files within the directory path $HOME/Downloads/backup:
To rename file1.txt to file10.txt we would implement the command:
$ mv file1.txt file10.txt
As expected, the file was successfully renamed. What if there were multiple file1.txt files on different directory paths and we wish to rename them instantaneously?
2. Rename Mulitple Files Using mv and find Commands
The find command searches for files from a specified directory path as its starting point, which is an inbuilt command and comes pre-installed on all major Linux distributions.
In our case, if we were to rename the above existing text files to have html files’ extension, the appropriate syntax to use would be:
$ find . -depth -name "[current/filename/element]" -exec sh -c 'f="{}"; mv -- "$f" "${f%[current/filename/element]}[new/filename/element]"' \;
Implementing the above syntax gives us:
$ find . -depth -name "*.txt" -exec sh -c 'f="{}"; mv -- "$f" "${f%.txt}.html"' \;
Explanation of the options used in the above find command.
- find . starts the search from the current directory path.
- -depth processes all the parent directory content.
- -name points to the current filename extension that needs changing.
- -exec initiates the execution of the mv command based on matched files.
3. Rename Files Using Bash Script
To rename files using the bash script, first, you need to create a script file.
$ nano file_renamer.sh
Add the following content:
#!/bin/bash for f in $HOME/Downloads/backup/*.html; do mv -- "$f" "${f%.html}.pdf" done
Save and close the file.
Here, we are using For Loop expression to search for all HTML files inside the directory $HOME/Downloads/backup and then executing an mv command to rename the HTML files extension to PDF file extension.
Make the script executable and run it.
$ chmod +x file_renamer.sh $ sh file_renamer.sh
The command execution was a success.
Combining the mv command with the find command or using it inside a bash script provides effective solutions to renaming multiple files at once under a Linux operating system environment.
Do you know any other way of renaming files in Linux? do share your views on the same in the comments section below.