1

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

pathtodelete1.txt
pathtodelete2.txt
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? – glenn jackman Oct 3 '18 at 20:47
  • No... Hence the question. – novice Oct 3 '18 at 23:05
2

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 – roaima Oct 3 '18 at 20:09
  • 1
    Just a caution: filenames that contain newlines (unusual but possible) will throw errors trying to remove them. – glenn jackman Oct 3 '18 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 Oct 3 '18 at 20:51
  • 1
    @ilkkachu you can change the delimiter for xargs with -d '\n' – novice Oct 3 '18 at 23:04
  • 1
    @novice, in GNU xargs, yes – ilkkachu Oct 4 '18 at 9:48
0
while read TXT; do head -1 $TXT | xargs rm; done < list.txt
0

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.

#!/bin/bash
# Look in list.txt for files containing items to delete
while IFS= read -r file
do
    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" ]]
    then
        echo "> $path" >&2
        : rm -f "$path"
    fi
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 – roaima Oct 3 '18 at 20:30
  • @don_crissti I think that's better now – roaima Oct 3 '18 at 20:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.