Unix: How to delete files listed in a file

后端 未结 13 1554
遥遥无期
遥遥无期 2020-12-04 06:31

I have a long text file with list of file masks I want to delete

Example:

/tmp/aaa.jpg
/var/www1/*
/var/www/qwerty.php

I need delet

相关标签:
13条回答
  • 2020-12-04 06:56

    In this particular case, due to the dangers cited in other answers, I would

    1. Edit in e.g. Vim and :%s/\s/\\\0/g, escaping all space characters with a backslash.

    2. Then :%s/^/rm -rf /, prepending the command. With -r you don't have to worry to have directories listed after the files contained therein, and with -f it won't complain due to missing files or duplicate entries.

    3. Run all the commands: $ source 1.txt

    0 讨论(0)
  • 2020-12-04 06:57

    Assuming that the list of files is in the file 1.txt, then do:

    xargs rm -r <1.txt
    

    The -r option causes recursion into any directories named in 1.txt.

    If any files are read-only, use the -f option to force the deletion:

    xargs rm -rf <1.txt
    

    Be cautious with input to any tool that does programmatic deletions. Make certain that the files named in the input file are really to be deleted. Be especially careful about seemingly simple typos. For example, if you enter a space between a file and its suffix, it will appear to be two separate file names:

    file .txt
    

    is actually two separate files: file and .txt.

    This may not seem so dangerous, but if the typo is something like this:

    myoldfiles *
    

    Then instead of deleting all files that begin with myoldfiles, you'll end up deleting myoldfiles and all non-dot-files and directories in the current directory. Probably not what you wanted.

    0 讨论(0)
  • 2020-12-04 06:59

    cat 1.txt | xargs rm -f | bash Run the command will do the following for files only.

    cat 1.txt | xargs rm -rf | bash Run the command will do the following recursive behaviour.

    0 讨论(0)
  • 2020-12-04 07:02

    This is not very efficient, but will work if you need glob patterns (as in /var/www/*)

    for f in $(cat 1.txt) ; do 
      rm "$f"
    done
    

    If you don't have any patterns and are sure your paths in the file do not contain whitespaces or other weird things, you can use xargs like so:

    xargs rm < 1.txt
    
    0 讨论(0)
  • 2020-12-04 07:04

    Just to provide an another way, you can also simply use the following command

    $ cat to_remove
    /tmp/file1
    /tmp/file2
    /tmp/file3
    $ rm $( cat to_remove )
    
    0 讨论(0)
  • 2020-12-04 07:06

    Here you can use set of folders from deletelist.txt while avoiding some patterns as well

    foreach f (cat deletelist.txt)
        rm -rf ls | egrep -v "needthisfile|*.cpp|*.h"
    end
    
    0 讨论(0)
提交回复
热议问题