How to delete files listed in a text file

Use xargs:

xargs rm < file  # or
xargs -a file rm

But that will not work if the file names/paths contain characters that should be escaped.

If your filenames don't have newlines, you can do:

tr '\n' '\0' < file | xargs -0 rm # or
xargs -a file -I{} rm {}

Alternatively, you can create the following script:

#!/bin/bash

if [ -z "$1" ]; then
    echo -e "Usage: $(basename $0) FILE\n"
    exit 1
fi

if [ ! -e "$1" ]; then
    echo -e "$1: File doesn't exist.\n"
    exit 1
fi

while read -r line; do
    [ -n "$line" ] && rm -- "$line"
done < "$1"

Save it as /usr/local/bin/delete-from, grant it execution permission:

sudo chmod +x /usr/local/bin/delete-from

Then run it with:

delete-from /path/to/file/with/list/of/files

Here's one way that can deal with file names with whitespace, backslashes and other strange characters:

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

That will read each line of list.txt, save it as $file and run rm on it. The -r ensures that backslashes are read literally (so that \t matches a \ and a t and not a TAB). The -- ensures that it also deals with file names starting with -.

You could also do this in Perl:

perl -lne '$k{$_}++; END{unlink for keys(%k)}' list.txt

This one wil read each file name into the %k hash and then use unlink to delete each of them.


Through python.

import sys
import os
fil = sys.argv[1]
with open(fil) as f:
    for line in f:
        os.remove(line.rstrip('\n'))

Save the above script in a file named like script.py and then execute the script by firing the below command on terminal.

python3 script.py file

file is an input file where the path of the files you actually want to remove are stored.