Linux - 如何在文件名中间添加增量数字? [关闭]

问题描述 投票:-1回答:2

我已经看到大量的答案显示如何添加到文件的开头或结尾,但我正在寻找替换文件中间的数字。我有,例如:

ShowName - S00E01 - Episode Name.mkv
ShowName - S00E02 - Episode Name.mkv
ShowName - S00E03 - Episode Name.mkv

我想将E01-E03部分更改为E20到E22或类似的部分,而不修改文件名的其余部分。

无法弄清楚如何使用linux的“重命名”调用,任何其他建议吗?

linux bash rename
2个回答
1
投票

Linux实用程序rename只是一个简单的工具。使用正则表达式的更高级工具是perl-rename,它通常单独安装。但它仍然无法解决您的问题。

对于任何更复杂的事情,我通常会尝试编写一个小的bash for loop。 例如。此脚本应该适用于您的问题:

# for every file ending with .mkv
for f in *.mkv; do
        # transform the filename using sed, so that character '|' character will separate episode number from the lest of the filename (so it can be extracted)
        # e.g. 
        # 'ShowName - S00E01 - Episode Name.mkv' will be 
        # 'ShowName - S00E|01| - Episode Name.mkv'
        # Then read such string to three variables:
        # prefix enum and suffix splitting on '|' character
        IFS='|' read -r prefix enum suffix < <(sed 's/\(.*S[0-9][0-9]E\)\([0-9][0-9]\)\(.*\)/\1|\2|\3/' <<<"$f");
        # newfilename consist of prefix, calculated episode number and the rest of the filename
        # i assumed you want to add 19 to episode number
        # it may be also a good idea to move files to another directory, to avoid unintentional overwriting of existing files
        # you may also consider using -n/--no-clobber or --backup options to mv
        newf="another_directory/${prefix}$(printf "%02d" "$((enum-1+20))")${suffix}"
        # move "$f" to "$newf"
        # filenames have special characters (spaces), so remember about qoutes 
        echo "'$f' -> '$newf'"
        mv -v "$f" "$newf"
done

1
投票

使用grep等其他工具来帮助您:

for f in *.mkv; do
  NUM=$(echo "$f" | grep -Po '(?<=E)[0-9]{2}')
  NEWNUM=$((NUM+20))
  fn=${f/E${NUM}/E${NEWNUM}}
  mv "$f" "$fn"
done

其余的应该可以通过shell的内置字符串替换功能轻松完成。

© www.soinside.com 2019 - 2024. All rights reserved.