0

I am trying to delete old files, I first need to store the files in a variable and delete them one by one, my code works for normal files but if filename has white spaces in it, it cant delete that file and throws an error

code-

OLD_FILES=`find . -name "*.txt" -type f -newermt $2000-01-01 ! -newermt $2017-12-12`
for i in $OLD_FILES
   do
     rm $i
   done

I can't use

OLD_FILES=`find . -name "*.$FILE_TYPE" -type f -newermt $START_DATE ! -newermt $DATE -delete `

because find and delete needs to be separate functions and to avoid code repetition

  • `find` can print and remove the files in one go. If you genuinely think you cannot drive a loop with `find` then a string variable in unsuitable for unambiguously storing file names. Perhaps see https://stackoverflow.com/questions/34555278/bash-read-a-looping-on-null-delimited-string-variable for how to store `find` results in an array in Bash. – tripleee Dec 07 '17 at 08:45

2 Answers2

1

Filenames on UNIX may contain more or less any character, especially characters which are used by the shell to split input into words, like whitespace and newlines. If you use a for in loop, word splitting happens and that's what you are seeing.

I recommend to use the -print0 option of find which would separate files by null bytes and then use while read with the null byte as the delimiter to read them in the shell one by one:

find ... -print0 | while read -d $'\0' file ; do
    do_something "${file}"
    rm "${file}"
done
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
0

Have a look at the following link https://unix.stackexchange.com/questions/208140/deleting-files-with-spaces-in-their-names

There are many solutions you might be able to apply to your problem:

  • like deleting the files via their inum
  • using a regex with space to fetch the file: find . -regex '.* .*' -delete
  • using xargs and find . -type -f -print 0
  • make a function to escape all spaces of your filenames \, before running the rm command
Allan
  • 12,117
  • 3
  • 27
  • 51