Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix: How to delete files listed in a file

Tags:

linux

unix

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 delete them. Tried rm `cat 1.txt` and it says the list is too long.

Found this command, but when I check folders from the list, some of them still have files xargs rm <1.txt Manual rm call removes files from such folders, so no issue with permissions.

like image 268
Alexander Avatar asked Feb 28 '11 13:02

Alexander


People also ask

How do you delete part of a file in Linux?

To remove selected parts of lines from each FILE, we use the cut command in the Linux system. The cut command is used to remove and print the selected section of each FILE in the Linux operating system using a terminal. It is also used to cut the selected parts of a line by byte position, character, and field.

How do I delete old files in Unix?

If you want to delete files older than 1 day, you can try using -mtime +0 or -mtime 1 or -mmin $((60*24)) .

How do I delete multiple files in Unix?

To delete multiple files at once, simply list all of the file names after the “rm” command. File names should be separated by a space. With the command “rm” followed by multiple file names, you can delete multiple files at once.


2 Answers

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 
like image 192
nos Avatar answered Sep 29 '22 20:09

nos


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.

like image 33
aks Avatar answered Sep 29 '22 19:09

aks