Batch Rename Files in Linux(批量重命名linux)
Using Script
It is common to find ourselves in a situation where we have to batch rename multiple files in Linux. It is a typical scenario that is faced by many users of the OS. Fortunately, Linux provides several simple ways to batch rename files. In this article, we will discuss one of the easiest methods – using a script to batch rename files in Linux.
The first step is to create the script. To do this, open a text editor like Nano, Vim, or Gedit. The best practice is to name the script based on the task it is meant to carry out, thus making it easier to find and launch when the time comes to use it. Once the script is ready, save it as a .sh file in a convenient location.
Once the script is created, open a terminal and navigate to the directory containing the files that need to be renamed. To batch rename files using the script, execute the following command:
$ sh script_name.sh *.txt
In this example, the files we want to batch rename using our script have the .txt extension. The asterisk is used to refer to all the relevant files in the folder.
When carrying out a batch rename process, it is important to be sure that we have the right script in place. To do this, we can view the files in the directory with the ls command and examine the command being used in the script. This will help us double-check that all the files we have identified will be renamed correctly.
Most scripts used for batch rename tasks are highly customizable to accommodate different scenarios. To batch rename the files with their serial numbers, we can modify the script by adding the following code:
#!/bin/bash
i=1
for file in *
do
mv “$file” “file$i.txt”
let i=i+1
done
This code removes the old filenames and attaches the serial numbers to the new filenames. The files will now be renamed according to the following format: file1.txt, file2.txt, etc.
Finally, in order to execute the script and rename the files, we simply enter the following command in the terminal:
$ sh script_name.sh *.txt
The command will look for all the files with the .txt extension, and renaming them with their serial numbers.
In conclusion, batch renaming files in Linux can be done quite easily with a script, instead of going through the tedious process of renaming files manually. With this approach, users can easily make all the necessary changes at once with minimal effort.