linux rename的实现

发布时间 2023-08-03 11:09:02作者: xuyv

linux rename可以批量重命名文件。
rename expression replacement files

可以用bash实现:
遍历文件file,用sed等替换file中的字符串,mv $file echo $file | sed -i 's/expression/replacement/'
也可以用bash内置的parameter expansion替换。
代码如下:

#!/bin/bash

# Prompt the user for the search and replace strings
echo "Enter the string to search for: "
read search_string
echo "Enter the string to replace it with: "
read replace_string

# Loop through all files in the current directory
for file in *; do
    # Check if the file name contains the search string
    if echo "$file" | grep -q "$search_string"; then
        # Rename the file, replacing the search string with the replace string
        mv "$file" "${file/$search_string/$replace_string}"
        echo "Renamed $file to ${file/$search_string/$replace_string}"
    fi
done