I have one text file with names of a bunch of .txt files (not full path names) that exist in a directory. Each of the files, have a (full) path to another file which I would like to delete.

Suppose I have a file named "list.txt" and in it there are names of text files

something else that is the same as pathtodelete.txt

Each one of these files has a one path stored inside, for example pathtodelete1.txt contains /directory/randomfilename.txt

I have tried putting together xargs in many ways with no success.

  • This seems pretty convoluted. Can't you keep a single file with the paths to delete? Commented Oct 3, 2018 at 20:47
  • No... Hence the question.
    – novice
    Commented Oct 3, 2018 at 23:05

3 Answers 3


In a limited test, this worked for me:

cat list.txt | xargs cat | xargs rm

Since you are using this to delete files, you might want to test it with a non-destructive command first, e.g.

cat list.txt | xargs cat | xargs echo
  • 1
    UUOC xargs cat <list.txt | xargs -r rm Commented Oct 3, 2018 at 20:09
  • 1
    Just a caution: filenames that contain newlines (unusual but possible) will throw errors trying to remove them. Commented Oct 3, 2018 at 20:47
  • 1
    xargs by default also splits the input on any white space, so this won't work if any of the files involved have white space in their names. (like the one in the example)
    – ilkkachu
    Commented Oct 3, 2018 at 20:51
  • 1
    @ilkkachu you can change the delimiter for xargs with -d '\n'
    – novice
    Commented Oct 3, 2018 at 23:04
  • 1
    @novice, in GNU xargs, yes
    – ilkkachu
    Commented Oct 4, 2018 at 9:48
while read TXT; do head -1 $TXT | xargs rm; done < list.txt

This script should do what you want. You can comment the echo statements (or omit them entirely) if you don't want a report on what it is doing.

Remove the : from the beginning of the rm statement when you are satisfied it will do what you want, and then it really will delete the named files.

# Look in list.txt for files containing items to delete
while IFS= read -r file
    echo "Considering $file" >&2

    # Read the path to delete from the file
    path="$(cat "$file" 2>/dev/null)"

    # If it looks like a pathname try to delete it
    if [[ "$path" =~ ^/ ]] && [[ -f "$path" ]]
        echo "> $path" >&2
        : rm -f "$path"
done <list.txt
  • I was trying to work out whether list.txt was an example of "one of the files". Re-reading the question again, after your comment I'll revisit the code. Thanks @don_crissti Commented Oct 3, 2018 at 20:30
  • @don_crissti I think that's better now Commented Oct 3, 2018 at 20:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .