Find Command – How to Move All Files Except One Matching Filename

findmv

I want to move all files in my current directory to a directory named NewDir that end with *.bam, except for a specific file named special.file.bam.

I have found this command that removes all files, but not sure how to move them, not deleting them:

find . ! -name 'special.file.bam' -type f -exec rm -f {} +

Best Answer

If your shell is the bash shell, you can simply do as following by enabling the Extended Glob:

shopt -s extglob
mv -- !(special.file).bam temp/

to suppress the error:"bash: /usr/bin/mv: Argument list too long" when there are too many files matching the given pattern, do as following:

for file in !(special.file).bam; do
    mv -- "$file" temp/
done

or with the find command instead and portability:

find . -path './*' -prune -type f -name '*.bam' ! -name 'special.file.bam' \
    -exec sh -c 'for file; do mv "$file" temp/; done' sh_mv {} +

remove -path './*' -prune part to find files in sub-directories too.

Related Question