Home  >  Article  >  System Tutorial  >  Use an example to explain the use of regular expressions in the rename command

Use an example to explain the use of regular expressions in the rename command

王林
王林forward
2024-04-07 08:04:01863browse

Use an example to explain the use of regular expressions in the rename command

#rename commandBatch change file names using string replacement. Today I will use an example to write down in detail the problems I encountered and how I solved them. I hope everyone has to help.

The format is as follows:

rename original string target string file (list)
  1. Original string: the string that needs to be replaced with the file name;
  2. Target string: Replace the original characters contained in the file name with the target string;
  3. File: Specify the file list to change the file name.
Example:
Rename main1.c to main.c
rename  main1.c  main.c  main1.c
rename supports wildcard characters
?  可替代单个字符
*  可替代多个字符
[charset]  可替代charset集中的任意单个字符

Example:

There are these files foo1, ..., foo9, foo10, ..., foo278

in the folder
rename foo foo0 foo?

This command will rename the files from foo1 to foo9 to foo01 to foo09. The renamed files are only files with a 4-character name, and foo in the file name is replaced with foo0.

rename supports regular expressions

Now let’s use a specific example to explain the use of regular expressions in this command:

The data (pictures) in my hand this afternoon are named (1).jpg, (2).jpg...to (16720).jpg.

Now I want to change the file name to 00001.png, 00002.png,...16720.png

Step one: Change the suffix name .jpg to .png

rename 's/\.jpg$/\.png/' *.jpg

Step 2: Remove the left bracket "(":

rename 's/^\(//' *.png

The third step is to remove the right bracket ")":

rename 's/\)//' *.png

Step 4: Change the file name to five digits, and add 0 in front of any number less than five digits. The creation of the script a.sh is completed. The content of the script is as follows:

#!/bin/bash
for i in {1..9}
do 
   mv $i.png  0000$i.png
done
for i in {10..99}
do 
   mv $i.png  000$i.png
done
for i in {100..999}
do 
   mv $i.png  00$i.png
done
for i in {1000..9999}
do 
   mv $i.png  0$i.png
done

Then put the script file and the folder where the file name needs to be changed, and we can directly execute the script.

If you see "Insufficient Permissions" at this time, just add execution permissions.

chmod  755 a.sh

At this point, we have completed the task. If there is anything you don’t understand, please leave me a message. If reprinted, please indicate the source: http://www.cnblogs.com/wongyi/

The above is the detailed content of Use an example to explain the use of regular expressions in the rename command. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:linuxprobe.com. If there is any infringement, please contact admin@php.cn delete