Home>Article>Operation and Maintenance> How to rename files using mv command in Linux? (code example)
Renaming files and directories is one of the most basic operations performed on a Linux system, so how to rename files? The following article will show you how to use mv to rename files (folders) in Linux. I hope it will be helpful to you. [Video tutorial recommendation:Linux tutorial]
Use the mv command to rename files
The mv command (short move time) is used to rename or move files from one location to another.
Basic syntax:
mv [OPTIONS] source destination
Parameters:
source: can be one or more files or directories
destination: Can be a single file or directory.
Note:
● If multiple file sources are specified, the destination must be a directory. In this case, the source files will be moved to the target directory.
●If a single file is specified as source and the destination is an existing directory, the file will be moved to the specified directory.
● To rename a file, you need to specify a single file as the source and a single file as the destination.
For example, to rename the file file1.txt to file2.txt, you can execute the following command:
mv file1.txt file2.txt
How to use the mv command to rename multiple files?
The mv command can only rename one file at a time, but it can be used with other commands such as find in a bash for or while loop to rename multiple files.
Example: How to rename all .html files in the current directory, changing the .html extension to .php by using a bash for loop.
for f in *.html; do mv -- "$f" "${f%.html}.php" done
Let’s analyze the code line by line:
● The first line creates a for loop and traverses a list of all files.html.
● The second line applies to each item in the list and moves the file to a new one replacing .html with .php. The section ${file%.html} uses the shell parameter extension .html to remove the part from the file name.
● done indicates the end of the loop segment.
We can also use the command find in combination with mv to achieve the same function as above.
find . -depth -name "*.html" -exec sh -c 'f="{}"; mv -- "$f" "${f%.html}.php"' \;
The find command uses this switch to pass all .html files ending in the current directory mv to the command -exec one by one. The string {} is the name of the file currently being processed.
As you can see from the above example, using the mv command to rename multiple files is not an easy task as it requires a good understanding of Bash scripting.
Related recommendations: "How to use the rename command to rename files in Linux?》
The above is the detailed content of How to rename files using mv command in Linux? (code example). For more information, please follow other related articles on the PHP Chinese website!