Remove directories from a file with list of directories

2

1

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)?

Adam Schiavone

Posted 2012-02-22T15:46:53.643

Reputation: 185

Answers

4

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
/path/to/file_2

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.

slhck

Posted 2012-02-22T15:46:53.643

Reputation: 182 472

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 – 2015-12-05T04:54:35.377

File name too long – chovy – 2015-12-05T05:22:51.853

1From 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 – 2015-12-06T20:21:01.483

the list is too long. if i have 1000+ files to delete its too long for xargs – chovy – 2015-12-07T07:21:53.083

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 – 2015-12-07T12:28:04.850

1

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

Frg

Posted 2012-02-22T15:46:53.643

Reputation: 236

this doesn't suffer from argument list too long errors. upvoting. – chovy – 2015-12-07T07:22:21.343