Batch Renaming in Linux Made Easier(批量重命名linux)

It often happens that we need to rename a large set of files or folders quickly. In order to do this, there are Linux-based commands that can be used to facilitate batch renaming.

One such command is ‘rename’ which is used to rename the filename(s) or directory(ories). The syntax for this command is as follows:

rename [OPTION]… [MODIfiER]… FILE…

In order to change the name of each file respectively, the ‘modifier’ is required. It consists of a pair of target and replacement-patterns separated by transfer characters.

For example, if your file is named ‘sample_file_example’ and you want to change this to ‘sample-file-example’, then the command would be as follows:

rename ‘s/_/-/’ sample_file_example

It is also possible to use Regex to modify the files in a batch. Most commonly used modifiers are s///, y///, which is used for substitution and transliteration, respectively.

If you want to rename all files in a directory, you can use the ‘find’ command in conjunction with the ‘rename’ command. The syntax for this would be as follows:

find [PATH] -name [NAME] -type [TYPE] | xargs -I % sh -c ‘rename [MODIfiER] “%”’

You can use the -name option to specify the filename to be renamed and the -type option to specify the type of files to be modified.

For example, if you want to change the name of all the .txt files in a particular directory to .log files, then you can use the following command:

find /directory -name “*.txt” -type f | xargs -I % sh -c ‘rename ‘s/\.txt$/\.log/‘ “%”’

Batch renaming in Linux can be made easier with these commands. However, care must be taken with wildcards and modifiers as they can result in unwanted effects if used incorrectly. It is always advisable to create a backup of your original files before using these commands.


数据运维技术 » Batch Renaming in Linux Made Easier(批量重命名linux)