Remove directories from a file with list of directories

5,192

Solution 1

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.

Solution 2

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:
5,192

Related videos on Youtube

Adam Schiavone
Author by

Adam Schiavone

Part time Student in Philadelphia, part time Software Engineer. I’ve been programming in C# since 2009 at least, and it’s a magical language in my opinion.

Updated on September 18, 2022

Comments

  • Adam Schiavone
    Adam Schiavone almost 2 years

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

  • chovy
    chovy over 8 years
    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
    chovy over 8 years
    File name too long
  • slhck
    slhck over 8 years
    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.
  • chovy
    chovy over 8 years
    the list is too long. if i have 1000+ files to delete its too long for xargs
  • chovy
    chovy over 8 years
    this doesn't suffer from argument list too long errors. upvoting.
  • slhck
    slhck over 8 years
    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.