Removing an excessive number of files from a directory - when 'rm' just isn't enough

From CUC3
Jump to navigation Jump to search

If you have say 10000 files, all named output.[number], trying to get rid of them all with the usual rm output.* command won't work as when you expand the * to produce the full rm command (i.e. rm output.1 output.2 ... output.10000), you get an error about there being too many arguments to rm - you're hitting some sort of hard limit.

You could of course delete the files in smaller blocks manually but there is a simpler way, using xargs and find.

find . -name "output.*" -print | xargs rm

Will do the job for you. The find command pipes the filenames (output.1, output2 etc) to xargs one at a time. xargs then executes the rm command for each filename it is passed separately. The above command is equivalent to:

rm output.1
rm output.2
.
.
.
rm output.10000

Job done! Care should of course be taken when using any command that removes files. If you're not 100% sure what your expression will do - ask someone to check it!

WARNING! This operation is RECURSIVE BY DEFAULT! It will remove all files that match the expression in the working directory AND any below it!

To remove only files in the working directory, use ls:

ls -1 output.* | xargs rm