乐闻世界logo
搜索文章和话题

How do you rename files in bulk using a shell script?

1个答案

1

When using shell scripts for batch renaming files, we can leverage the powerful command-line tools of Shell, such as mv, find, awk, etc., to achieve efficient file processing. Below, I will demonstrate how to use shell scripts for batch renaming files through specific examples.

Example Scenario

Suppose we have a set of files with naming format image1.jpg, image2.jpg, ..., image10.jpg. Now, we need to rename these files to photo1.jpg, photo2.jpg, ..., photo10.jpg.

Solution

Solution One: Using for Loop and mv Command

This is a simple and intuitive method that loops through all files and uses the mv command for renaming.

bash
#!/bin/bash for file in image*.jpg do # Use Bash's string replacement feature newname="${file/image/photo}" mv "$file" "$newname" done

In this script, we use Bash's pattern matching to match all image*.jpg files, and then within the loop, use the mv command to replace image with photo in the original filename.

Solution Two: Combining find Command and awk Script

If the files are distributed across multiple directories or we need more complex renaming rules, we can use the find command combined with an awk script to accomplish this.

bash
#!/bin/bash find . -type f -name 'image*.jpg' | awk ' { # Construct new filename newname = gensub(/image(.*)\.jpg$/, "photo\\1.jpg", "g", $0); # Print mv command print "mv ""$0"" ""newname"" }' | bash

In this approach, the find command first locates all files matching image*.jpg, then passes them through a pipe to awk. awk uses the gensub function to generate the new filename and prints the corresponding mv command. Finally, these commands are piped to bash for execution.

Notes

  • Before executing the renaming operation, it is recommended to print out the commands to be executed for verification.
  • Considering that filenames may contain special characters or spaces, it is best to use double quotes when referencing variables.
  • When using scripts for batch operations in production environments, it is advisable to test the script's correctness on a small-scale dataset first.

The above are two common methods for using shell scripts to batch rename files. These methods can not only be applied to simple renaming tasks but can also be modified and extended to meet more complex file processing requirements.

2024年8月14日 17:28 回复

你的答案