How to delete files listed in a text file

I have a text file that has a list of paths to various files. Is there a command I can use that will iterate through each line and delete the file at the stated path?


Solution 1:

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

Solution 2:

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.

Solution 3:

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.

Solution 4:

Silly, but here is one:

 tar -cvf /dev/null --remove-files -T filename

Solution 5:

Another way to do this:

You can 'prepare' the file by making it a shell script:

$ sed -E "s/^(.*)$/rm '\1'/" input_file
rm 'file1'
rm 'file2'
rm 'file with some spaces.ext'

If your filenames may have a single quote ('), you can use this slightly expanded version to escape them first:

$ sed -E "s/'/'\\\''; s/^(.*)$/rm '\1'/" input_file
rm 'file1'
rm 'file2'
rm 'file with some spaces.ext'
rm 'a file with "quotes"'
rm 'a file with '\''quotes'\'''

And you can run this by piping it to sh:

$ sed -E "s/'/'\\\''; s/^(.*)$/rm '\1'/" input_file | sh