Shell / script command to delete files whose names are in a text file

I have a list of files in a .txt file (say list.txt). I want to delete files from this list. I didn’t do scripts before. Can someone give a script / shell command that I can use. I have a bash shell.

+8
source share
6 answers
while read -r filename; do rm "$filename" done <list.txt 

slow.

 rm $(<list.txt) 

will fail if there are too many arguments.

I think it should work:

 xargs -a list.txt -d'\n' rm 
+35
source

Try the following command:

 rm -f $(<file) 
+9
source

If file names have spaces in them, none of the other answers will work; they will treat each word as a separate file name. Assuming the file list is in list.txt , this will always work:

 while read name; do rm "$name" done < list.txt 
+3
source

The following should work and leaves you a place to do other things while passing through.

Edit: do not do this, see here: http://porkmail.org/era/unix/award.html

for the file in $ (cat list.txt); do rm $ file; Done Strike>

+1
source

For quick execution on macOS, where xargs custom delimiter d not possible:

 <list.txt tr "\n" "\0" | xargs -0 rm 
+1
source

On Linux, you can try:

 printf "%s\n" $(<list.txt) | xargs -I@ rm @ 

In my case, my .txt file contained a list of elements of type *.ext and worked fine.

0
source

All Articles