9

I want to remove files that have not the string '999' (without the '') in their name.

I have tried:

grep -vlr 999 . | xargs -0 rm -f --
find . -print0 | grep --null-data -v 999 | xargs -0 rm --

But none of them works. I am using macOS Sierra, with bash: 3.2.57.

  • 2
    grep -l causes it to list the files where a match was found (or not found with -v) in the content, not the filename. grep always matches against the content of the files you specify, never their names. – JoL May 16 '18 at 0:52
17

Using an extended globbing pattern in bash:

rm ./!(*999*)

This requires shopt -s extglob to be enabled (and for safety, also shopt -s failglob, so that no file with the unusual name !(*999*) gets removed by mistake if all filenames contain 999). The pattern !(*999*) will match any name in the current directory, except those names matching *999*. To also remove hidden files (files whose name starts with a dot), also enable the dotglob option.

To only care about regular files or symbolic links to regular files (not directories etc.):

for name in ./!(*999*); do [ -f "$name" ] && rm "$name"; done

The zsh shell equivalent to the above loop would be

rm ./(^(*999*))(.)

Your first command will not work since grep will look inside files. It would remove all files that have lines without 999 in them (had you added the --null option so it works with xargs -0).

Your second command will not work since grep on macOS does not support --null-data (it does however have a --null option, but only for when generating filename output). Also note that it would look for 999 anywhere in the file's path (including directory components), not only the file's name.

  • 1
    You'd also want to enable the failglob option or it could end up removing the file called !(*999*) if there's no other file whose name doesn't contains 999. – Stéphane Chazelas Dec 9 '19 at 13:04
16

Just invert the name condition in find :

find . -type f \! -name "*999*" 

Add -delete or -exec rm {} + to actually remove the matched files.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.