Linux can't delete files

2020-04-14 08:37发布

问题:

I have a problem with removing files when I find them. Task : must find files with spaces and remove them

my try :)

rm $(find -L /root | grep -i ' ')

But i have errors:

rm: cannot remove `/root/test': No such file or directory
rm: cannot remove `2.txt': No such file or directory
rm: cannot remove `/root/test': No such file or directory
rm: cannot remove `3.txt': No such file or directory
rm: cannot remove `/root/test': No such file or directory
rm: cannot remove `1.txt': No such file or directory

Please help resolve this problem.

Thanks.

回答1:

Why not thus:

find /root -type f -name '* *' -exec rm -f {} ';'


回答2:

I'm guessing you are finding files with spaces in, or quotes. Try this:

find /test/path -print0 | xargs -0 rm

What this will do is send the filenames to stdout separate by NULL bytes, which xargs will take as delimiters. This allow spaces, quotes and other such fun in the output.

Now, if you are removing directories, rm is not going to work. So you might want to add a -type f to the above.

Note that gnu find itself has a -delete operator which will delete files for you, but you wanted to know why. Hence a shorter route would be:

find /test/path -delete

This will deal with directories too if you do not add -type f. It will also handle deleting the deepest things first (think about why this is needed).



回答3:

You can specify an -exec argument to the find command to run a command with the resulting file as an argument. In your case, the following command will do what you want.

-type f will print only files. If you want only directories then use -type d. If you use neither of these then it will print both files and directories.

As this is a delete operation, first run the command and see if it's printing the files you want.

find /root -type f -name '* *'

Then if everything is okay, run this to delete them.

find /root -type f -name '* *' -exec rm {} \;