用bash脚本批量修改文件名称(二)

前言:在上一篇文章中,我使用了warp模拟终端,让它教我写bash脚本来批量修改文件文称。这一篇则是优化,在保留文件扩展名的同时;根据文件数量,设置新文件名的对齐位(也就是有几十个文件时,从01开始编号;几百个文件时,则是从001开始。);并且可以选择是否添加前缀。
执行时输入“./rename.sh /path/files optional_prefix”即可,如果不需要前缀,最后一个参数改成noprefix即可。代码如下:

#!/bin/bash
# Change the file name accroding to the original order by digits
# while preserving the file extension.

# Check before running: Need 3 arguments to run the script properly
if [[ $# -lt 2 ]]; then
    echo "Didn't run, because the number of argument needs to be 2"
    echo "EX: $0 [/path/to/file] [new_name_prefix]"
    exit 0
fi

# 1. Get the old name files's directory and enter it
directory=$1
cd "$1"

# 2. Set the new name prefix
prefix=$2

# 3. Count the number of files in the directory
file_count=$(($(ls -l | grep -v '^d' | wc -l) -1))
echo "The total number of files to change name is $file_count."

# 4. Get the length of file_count
bits=${#file_count}
echo "The aligned number of the new name would be $bits."

# 5. Set the starting number
starting_number=1

# 6. Change to the new file name
if [ "$2" = "noprefix" ]; then
    # Loop through each file in the directory and rename without prefix
    for file in "$directory"/*; do

        # Get the current file name (basename is a command in shell)
        current_name=$(basename "$file")

        # Get the file extension
        extension="${current_name##*.}"

        # Generate the new file name
        new_name="$(printf "%0${bits}d"  "$starting_number").${extension}"

        # Rename the file
        mv "$file" "$directory/$new_name"

        ((starting_number++))
    done
else
    # Loop through each file in the directory and rename with prefix
    for file in "$directory"/*; do
    
        # Get the current file name
        current_name=$(basename "$file")
    
        # Get the file extension
        extension="${current_name##*.}"
    
        # Generate the new file name
        new_name="${prefix}-$(printf "%0${bits}d"  "$starting_number").${extension}"
    
        # Rename the file
        mv "$file" "$directory/$new_name"
    
        ((starting_number++))
    done
fi
echo "Complete. And the first 10 file is: $(ls | head -10)"
exit 0
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容