In work, sometimes it is necessary to modify the names of some files in batches, so in the case of a large amount, we have to learn to use scripts to operate, which saves time and effort.
1. Generate executable files
Tip: Before performing the modification operation, we first create an executable file.
1. Create a new file without a suffix, for example, the file name is rename .
2. Open the terminal, and cd to the directory where rename is located.
3. Enter the command sudo chmod u+x rename in the terminal .
4. After the execution is successful, the rename file becomes an executable file.
2. Edit the rename file
1. For the convenience of testing, I prepared a 0icon folder, which contains some folders and files, as shown in the figure below.
2. We change the first character of all files to " x ", and edit the rename file.
#!/bin/bash
function rename()
{
cd $1
echo $1
cfilelist=$(ls -A)
for cfilename in $cfilelist
do
if [[ $cfilename != .DS_Store ]]
then
mv $cfilename $'x'${
cfilename:1} # 语句1
fi
done
}
rename $1
Open the terminal and directly drag the rename file in ( don’t press Enter at this time, and don’t enter other characters ); then, drag the 0icon folder in, and then click Enter at this time, and after performing the operation, our The file initials have been replaced with x.
3. We add " mg_ " before the first character of all files, and edit the rename file, only need to modify "statement 1" to the following sentence.
mv $cfilename $'mg_'$cfilename # 语句2
Open the terminal and perform the same operation as above to modify our file name. As shown below.
4. Added " mg_ " in the previous step, we will delete it in this step, edit the rename file, just modify "statement 2" to the following three sentences, and these three sentences are collectively called "statement 3 ".
# 语句3
s=$cfilename
arr=(${
s//_/ })
mv $cfilename ${
arr[1]}
Open the terminal and perform the same operation as above to modify our file name. The name is back to the same as in article 2.
5. Finally, let's do a different operation. We need to rename the first folder to " GGG " through code, and move other files into this folder. To edit the rename file, you only need to modify "statement 3" to the following sentence.
s=$cfilename
arr=(${
s//_/ })
mv $cfilename $'GGG'${
arr[1]}
After execution, we can see that the structure has changed to the following, aaa is gone, and " GGG " is added , and the file directory has changed accordingly.
Afterword
These few commands in the script can be modified, you can try to modify it to see what the result will be.
In addition, if you want to know more, you can check out the article Using shell scripts to delete files with specified suffixes , I hope it will help you.