Search code examples
fish

Fish Shell: Delete All Except


Using Fish, how can I delete the contents of a directory except for certain files (or directories). Something like rm !(file1|file2) from bash, but fishier.


Solution

  • There is no such feature in fish - that's issue #1444.

    You can do something like

    rm (string match -rv '^file1$|^file2$' -- *)
    

    Note that this will fail on filenames with newlines in them.

    Or you can do the uglier:

    set -l files *
    for file in file1 file2
        if set -l index (contains -i -- $file $files)
            set -e files[$index]
        end
    end
    rm $files
    

    which should work no matter what the filenames contain.

    Or, as mentioned in that issue, you can use find, e.g.

    find . -mindepth 1 -maxdepth 1 -type f -a ! \( -name 'file1' -o -name 'file2' \)