使用 Linux 批量重命名文件(批量重命名linux)

Nowadays, Linux is widely used in our daily life and work. Releasing users from managing files through tedious mouse clicks, Linux has provided great convenience for us to manage files. Especially in the case of renaming multiple files, using Linux commands to conduct batch operation for our applications is a really effective way.

Take the case of using Linux to rename pictures as an example. Suppose we have a folder containing multiple pictures whose names are in a chaotic pattern. We can use the following command to easily rename them “Image_1.jpg”, “Image_2.jpg” and so on.

`cd`

`for i in {1..50} ; do mv Image.jpg Image_${i}.jpg; done`

Basically, what this command does is looping through “1 to 50” and use “mv” attribute to execute the renaming process while substituting the suffix “Image_${i}.jpg”.

But if we want to go further and customize the naming pattern, and also avoid name conflicts (e.g., Image_2.jpg already exists), we may need more complex commands:

`ls|grep “Image”|cut -d “.” -f 1|xargs -I file num=`ls|grep “Image”|grep -c “^file”`; mv file.jpg Image_${num}.jpg`

The command is composed of different segments.

`ls` is used to check all the files in the current folder, `grep “Image”` is to limit the names of files to “Image” and `cut -d “.” -f 1` is to get rid of suffix.

`xargs` converts the output of “ls|grep “Image”” as the input parameter of “num=`ls|grep “Image”|grep -c “^file”`”, which is used to generate a number after “Image_”.

At last, `mv file.jpg Image_${num}.jpg` is to complete the renaming process.

By carrying out the commands above, we can easily customize the naming patterns for our files and make them in order without conflicts. Hope this article has offered you a good insight into the way of using Linux to rename multiple files.


数据运维技术 » 使用 Linux 批量重命名文件(批量重命名linux)