V
V
vlarkanov2018-08-22 18:01:56
bash
vlarkanov, 2018-08-22 18:01:56

BASH: how to delete files whose names contain spaces?

There is a directory /mnt/hdd-backup/APPOLO/Backup Job APPOLO containing files with names like

Backup Job APPOLO2018-08-22T125035.vbk

It is necessary to delete files older than a certain period (in the example 9 minutes) I
execute:

find "$path" -type f -mmin +9 | xargs rm

I get:

rm: cannot remove '/mnt/hdd-backup/APPOLO/Backup': No such file or directory
rm: cannot remove 'Job': No such file or directory
rm: cannot remove 'APPOLO/Backup': No such file or directory
rm: cannot remove 'Job': No such file or directory
rm: cannot remove 'APPOLO.vbm': No such file or directory

Yeah. xargs can't handle spaces with paths. And if through for each?

oldfiles=$(find "$path" -type f -mmin +9)
for oldfile in $oldfiles
do
rm $oldfile 2>> $flog
done

And here's what:

rm: cannot remove '/mnt/hdd-backup/APPOLO/Backup': No such file or directory
rm: cannot remove 'Job': No such file or directory
rm: cannot remove 'APPOLO/Backup': No such file or directory
rm: cannot remove 'Job': No such file or directory
rm: cannot remove 'APPOLO.vbm': No such file or directory

How to win, comrades?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Saboteur, 2018-08-27
@vlarkanov

1. change the delimiter for xargs and find to the null character, both of these commands know about it:
2. Delete the files by the find command itself: 3. Save the list of files to a variable and read line by line:

A=$(find "$path" -type f -mmin +9)
while read; do rm "$REPLY";done<<<"$A"

J
jcmvbkbc, 2018-08-22
@jcmvbkbc

I execute:
find "$path" -type f -mmin +9 | xargs rm
...
Yup. xargs can't handle spaces with paths.
Idiom for handling filenames with spaces/whatever: find ... -print0 | xargs -0 ...-- i.e. use the null character as a field separator when output from find and when input to xargs.

D
Denis, 2018-08-22
@notwrite

man find says "Use -delete, user"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question