简体   繁体   中英

How to add a constant to the number included in filenames in python or bash script?

Say I have the following files:

file1900.txt file1901.txt file1902.txt ... file1998.txt file1999.txt file0.txt file1.txt file2.txt file3.txt ... file19.txt file20.txt

Now I want to add a constant 2000 to all the files where the numbers included in the filename are less than 1900 . Below is how I want to rename these files:

file1900.txt file1901.txt file1902.txt ... file1998.txt file1999.txt file2000.txt file2001.txt file2002.txt file2003.txt ... file2019.txt file2020.txt

Is there any good python script for this? Linux bash script is also fine if it's easier.

This following Python script uses a regular expression to match the general pattern you've provided, with the number in a matching group.

If the number is below 1900, it adds a 2000 to it and then calls os.rename to rename the file.

import re
import os

expression = re.compile(r'file(\d+)\.txt')

for item in os.scandir():
    if item.is_file():
        match = expression.match(item.name)
        if match:
            num = int(match.group(1))
            if num < 1900:
                num += 2000
                new_name = f"file{num}.txt"
                os.rename(item.name, new_name)

You can do it this way in bash.


FILES="file*.txt"
# loop through files in current dir
for file in $FILES                     
do
    #extract file number
    num=`echo $file | tr -dc '0-9'`    
    if [ "$num" -lt "$min_num" ]; then 
        # increment file number if it is less than 1900
        num_new=`expr $num + 2000`     
        # replace number with new one
        file_new=`echo $file | sed -e "s/$num/$num_new/g"`
        # rename file
        mv $file $file_new             
    fi

done```

If your requirement comes from working with "years" in filenames, it might make sense to add 2000 only to number less than 1000.

In this case you can simply use the Linux rename command with perl regex:

rename 's/(\d{1,3})(\.txt)/($1+2000).$2/e' file?.txt file??.txt file???.txt

file?.txt file??.txt file???.txt apply rename only to files file0.txt, ... file10.txt, ... file999.txt

(\\d{1,3})(\\.txt) - catches all one/two/three digit numbers before ".txt"

($1+2000).$2 - replaces the found numbers ($1) by "number+2000" and re-adds the catched ".txt" ($2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM