Renaming files and directories is a common task in Linux, and the command line provides a powerful and efficient way to perform these operations. In this article, we’ll explore the various commands and examples for renaming files and directories using the terminal.
Using the mv Command
The mv
command in Linux is not only for moving files but also for renaming them. Here’s a basic syntax for renaming a file:
mv old_filename new_filename
For example, the following command will rename file.txt
to newfile.txt
.
mv file.txt newfile.txt
Batch Renaming with the rename Command
The rename
command is handy for batch renaming files based on a pattern. It uses regular expressions to match and replace file names.
rename 's/old_prefix/new_prefix/' *.txt
In this example, all files with the .txt
extension will have their names changed by replacing ‘old_prefix’ with ‘new_prefix’.
Renaming Directories
To rename a directory, you can use the mv
command similarly to renaming files.
mv old_directory new_directory
This command will rename ‘old_directory’ to ‘new_directory’.
Appending a Prefix or Suffix
If you want to add a prefix or suffix to a file or directory name, you can use a combination of commands like mv
and echo
.
mv file.txt prefix_$(basename file.txt)
This appends ‘prefix_’ to the beginning of the file name.
Replacing Spaces with Underscores
Dealing with spaces in file names can be challenging. To replace spaces with underscores, you can use the rename
command.
rename 's/ /_/g' *
This command replaces all spaces with underscores for all files in the current directory.
Using the find Command for Complex Renaming
The find
command, combined with the exec
option, can be powerful for renaming files based on various conditions.
find . -type f -name "*.jpg" -exec mv {} {}_backup \;
This command finds all JPEG files in the current directory and adds “_backup” to their names.
Renaming with Shell Parameter Expansion
Shell parameter expansion provides a concise way to manipulate variables, which can be useful for renaming files.
file="example.txt"
mv "$file" "${file%.txt}_new.txt"
This command renames ‘example.txt’ to ‘example_new.txt’ by leveraging parameter expansion to remove the ‘.txt’ extension.
Interactive Renaming with mmv
The mmv
command allows interactive renaming of files and directories using wildcards.
mmv "*.old" "#1.new"
This command renames all files with the ‘.old’ extension to have the same name but with ‘.new’.