Search code examples
fish

conditionally rename files based on regex


I have this function "fileSuffix" which will rename "anything.mp3" to "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

I would like to change this functionality to:

1) check if the file has /\.\d+\./ and if so iterate the filename:

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

2) if the file doesn't have /\.\d+\./ then add ".1." between the extension and the filename

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

I don't know the best way to do this. I tried string split -r -m1 /\.\d+\./ "test.test.1.test" but it doesn't work


Solution

  • I'd write:

    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
    

    then

    $ 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
    

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