35

Normally to remove files with spaces in their filename you would have to run:

$ rm "file name"

but if I want to remove multiple files, e.g.:

$ find . -name "*.txt" | xargs rm

This will not delete files with spaces in them.

muru
  • 193,181
  • 53
  • 473
  • 722
Ashley
  • 497
  • 2
  • 6
  • 9
  • Complete guess here: does `find -name "*\ *.txt" | xargs rm` work for two word files? – TheWanderer Aug 26 '15 at 12:17
  • 1
    possible duplicate of [How to use find when there are spaces in the directory names?](http://askubuntu.com/q/148531/309110)  See also [how to avoid space in filename?](http://askubuntu.com/q/250874/309110) and [Problem with spaces in file names](http://askubuntu.com/q/621007/309110). – Scott - Слава Україні Aug 26 '15 at 18:23

3 Answers3

53

You can tell find and xargs to both use null terminators

find . -name "*.txt" -print0 | xargs -0 rm

or (simpler) use the built-in -delete action of find

find . -name "*.txt" -delete

or (thanks @kos)

find . -name "*.txt" -exec rm {} +

either of which should respect the system's ARG_MAX limit without the need for xargs.

steeldriver
  • 131,985
  • 21
  • 239
  • 326
  • 1
    Can't upvote it twice tough :) since you mentioned `ARG_MAX` I'll also mention that `find . -name "*.txt" -exec rm {} \;` would be a "safe shot" – kos Aug 26 '15 at 15:36
  • 3
    Thus sayeth the master: always remember xargs -0. – Joshua Aug 26 '15 at 19:46
  • 1
    Super important point: `-print0` must be the last option (or at least after `-name "*.txt"`) otherwise this will hit files *no longer limited to `*.txt`*... – Kev Sep 08 '18 at 09:49
1

The xargs command uses tabs, spaces, and new lines as delimiters by default. You can tell it to only use newline characters ('\n') with the -d option:

find . -name "*.txt" | xargs -d '\n' rm

Source answer on SO.

joseph_morris
  • 211
  • 1
  • 7
1

Incidentally, if you used something other than find, you can use tr to replace the newlines with null bytes.

Eg. the following one liner deletes the 10 last modified files in a directory, even if they have spaces in their names.

ls -tp | grep -v / | head -n 10 | tr "\n" "\0" | xargs -0 rm

Ibrahim
  • 158
  • 10