Remove files without string in name

plr 05/15/2018. 2 answers, 585 views
bash osx filenames rm

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 Answers


Kusalananda 05/16/2018.

Using an extended globbing pattern in bash:

rm ./!(*999*)

This requires shopt -s extglob to be enabled. The pattern !(*999*) will match any name in the current directory, except those names matching *999*.

To only care about regular files (not directories etc.):

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

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.


ilkkachu 05/15/2018.

Just invert the name condition in find :

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

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

Related questions

Hot questions

Language

Popular Tags