delete the files listed in a plain-text document

For all you crazy bash gurus out there.

I have a list of about 15 files I want to delete. They’re on their own line in a text file. how can I go about deleting them from the command line in one command string?

I mostly just doing this as a personal exercise in bash scripting. I think I understand the for loop thing, but I don’t know how to read a specific line number from my text file. Do I use head,sed,tr, cut?

thanks all!

rm $(cat list.txt)

in bash, assuming you wanted to delete every file listed

rm `cat list.txt`

for people who want to be compatible with Bourne shell.

If the filename is in a particular line you can use sed (among many choices) to pick out the line.

rm $(sed -n 15p something.txt)

picks out the 15th line and deletes the file named there.

That’s not the whole story though, you have to be careful about filenames with spaces and other characters, but this will do for a start.

rotfl! that was so easy - i didn’t even think of it. Some of the most complex things really aren’t all that complex. I appreciate you taking the time to read and answer this silly post. I hope to learn more about *nix and bash commands and syntax.

to make your script resilient, its still better to follow normal way, ie, to quote your variables. Since you are using bash, the normal way to read files is


while read -r line
do
 rm "$line"
done < "file_to_delete_files"

There is actually another trick you can employ and that is to convert the
's to \0’s and feed the output to xargs -0

Say your file contains:

a b
c
d
e f

tr '\012' '\0' < file.txt | xargs -0 rm

should do the job. No guarantees, if it breaks you can keep all the pieces, etc, etc. (Yes, it will fail on filenames with newlines in it. :))