Romonov
Romonov

Reputation: 8605

Shell command/script to delete files whose names are in a text file

I have a list of files in a .txt file (say list.txt). I want to delete the files in that list. I haven't done scripting before. Could some give the shell script/command I can use. I have bash shell.

Upvotes: 17

Views: 44060

Answers (7)

egarlock
egarlock

Reputation: 579

I was just looking for a solution to this today and ended up using a modified solution from some answers and some utility functions I have.

// This is in my .bash_profile

# Find
ffe () { /usr/bin/find . -name '*'"$@" ; } # ffe: Find file whose name ends with a given string

# Delete Gradle Logs
function delete_gradle_logs() {
   (cd ~/.gradle; ffe .out.log | xargs -I@ rm@)
}

Upvotes: 1

George
George

Reputation: 191

On linux, you can try:

printf "%s\n" $(<list.txt) | xargs -I@ rm @

In my case, my .txt file contained a list of items of the kind *.ext and worked fine.

Upvotes: 0

Cœur
Cœur

Reputation: 38667

For fast execution on macOS, where xargs custom delimiter d is not possible:

<list.txt tr "\n" "\0" | xargs -0 rm

Upvotes: 3

yamen
yamen

Reputation: 15618

The following should work and leaves you room to do other things as you loop through.

Edit: Don't do this, see here: http://porkmail.org/era/unix/award.html

for file in $(cat list.txt); do rm $file; done

Upvotes: 1

yazu
yazu

Reputation: 4650

while read -r filename; do
  rm "$filename"
done <list.txt

is slow.

rm $(<list.txt)

will fail if there are too many arguments.

I think it should work:

xargs -a list.txt -d'\n' rm

Upvotes: 50

Adam Liss
Adam Liss

Reputation: 48280

If the file names have spaces in them, none of the other answers will work; they'll treat each word as a separate file name. Assuming the list of files is in list.txt, this will always work:

while read name; do
  rm "$name"
done < list.txt

Upvotes: 5

Tim Pote
Tim Pote

Reputation: 28029

Try this command:

rm -f $(<file)

Upvotes: 12

Related Questions