根据正则表达式有条件地重命名文件

conditionally rename files based on regex

我有这个函数 "fileSuffix",它将 "anything.mp3" 重命名为 "anything.s.mp3"

https://gist.github.com/chapmanjacobd/4b07d0f64b64ac6fa70056aa44ec02a7

function fileSuffix
    set filen (string split -r -m1 . "$argv[1]")[1]
    set filex (string split -r -m1 . "$argv[1]")[2]
    echo $filen.$argv[2].$filex
end

我想将此功能更改为:

1) 检查文件是否有 /\.\d+\./,如果有则迭代文件名:

"test.1.mp3" -> "test.2.mp3"

2) 如果文件没有 /\.\d+\./,则添加“.1”。在扩展名和文件名之间

"test.mp3" -> "test.1.mp3"

我不知道执行此操作的最佳方法。我尝试了 string split -r -m1 /\.\d+\./ "test.test.1.test" 但它不起作用

我会写:

function incrFileSuffix
    for file in $argv
        set match (string match -e -r '(.+)\.(\d+)\.([^.]+)' $file)
        if test $status -eq 0
            set root $match[-3]
            set n (math $match[-2] + 1)
            set ext $match[-1]
        else
            set match (string match -e -r '(.+)\.([^.]+)' $file)
            if test $status -ne 0
                # file does not have a dot. what to do?
                return
            end
            set root $match[-2]
            set n 1
            set ext $match[-1]
        end
        echo mv $file $root.$n.$ext
    end
end

然后

$ incrFileSuffix foo

$ incrFileSuffix foo.bar
mv foo.bar foo.1.bar

$ incrFileSuffix foo.bar.2.baz
mv foo.bar.2.baz foo.bar.3.baz

参考 https://fishshell.com/docs/current/cmds/string-match.html