Ubuntu – How to delete files listed in a text file

command linefiles

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?

Best Answer

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