Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a list of directories in a text file and each of them need to be deleted. How can I read in that list into the command (rm -r or rmdir)?

share|improve this question
up vote 2 down vote accepted

The "more correct" solution would be the following:

xargs -I{} rm -r {} < files

This calls rm -r, where {} is replaced with the file name.

Why? Piping files with spaces to xargs will result in wrong arguments. Let's say your list of files looks like this:

/path/to/file 1

Then xargs rm -r < list.txt would try to delete /path/to/file, 1 and /path/to/file_2. Definitely not what you want. Always be aware of spaces in paths when piping from and to UNIX / Linux commands.

share|improve this answer
What is the -I{} doing here? Docs say "replace string". Also, does this work if the file paths from the deletion list have spaces in them? – chovy Dec 5 '15 at 4:54
File name too long – chovy Dec 5 '15 at 5:22
From the manpage: "Replace occurrences of replace-str in the initial-arguments with names read from standard input." Most importantly, it says, "Unquoted blanks do not terminate input items; instead the separator is the newline character." So, the < files makes xargs receive the list of files as standard input. Then, it calls the initial argument, rm -r, on every line (= file name) received. With the -I option the splitting is done based on newlines rather than spaces, which means that this operation is safe for file paths with spaces in them. I don't understand your other comment. – slhck Dec 6 '15 at 20:21
the list is too long. if i have 1000+ files to delete its too long for xargs – chovy Dec 7 '15 at 7:21
You can probably then do something like this: cat files | tr '\n' '\0' | xargs -0 rm -r – this replaces the newlines with ASCII null characters. xargs will then call rm for each of the received lines separately. – slhck Dec 7 '15 at 12:28

assuming you have paths with spaces in file list.txt - one path per line. Then the following way of invoking xargs will preserve spaces:

cat list.txt | xargs -d \\n rm -r
share|improve this answer
this doesn't suffer from argument list too long errors. upvoting. – chovy Dec 7 '15 at 7:22

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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