将文件保存在变量中并删除文件

时间:2017-12-07 08:22:55

标签: bash shell unix

我正在尝试删除旧文件,我首先需要将文件存储在变量中并逐个删除它们,我的代码适用于普通文件,但如果文件名中有空格,则无法删除该文件并抛出错误

代码 -

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

我无法使用

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

因为查找和删除需要是单独的函数并避免代码重复

2 个答案:

答案 0 :(得分:1)

UNIX上的文件名可能包含或多或少的任何字符,尤其是shell用于将输入拆分为单词的字符,如空格和换行符。如果您使用for in循环,word splitting happens以及您所看到的内容。

我建议使用-print0 find选项,它将文件与空字节分开,然后使用while read和空字节作为分隔符,在shell中读取它们之一:

find ... -print0 | while read -d $'\0' file ; do
    do_something "${file}"
    rm "${file}"
done

答案 1 :(得分:0)

查看以下链接 https://unix.stackexchange.com/questions/208140/deleting-files-with-spaces-in-their-names

您可以将许多解决方案应用于您的问题:

  • 喜欢通过public void copyFiles(File source, File dest) { Collection<File> all = new ArrayList<File>(); try { addTree(source, all); for (File elem : all) { int p = 1; File newFile = new File(dest.toString() + "\\" + elem.getName().replace(".", " ("+p+").")); if (findFile(elem.getName(), dest)) { for (int x = 1; newFile.exists() == true; x++) { newFile = new File(dest.toString() + "\\" + elem.getName().replace(".", " ("+x+").")); } FileUtils.copyFile(elem.getAbsoluteFile(), newFile); // jika file TIDAK di hidden maka copy file ke direktori } else if (!(elem.isHidden())) { FileUtils.copyFileToDirectory(elem, dest); } } } catch (Exception e) { e.printStackTrace(); } }
  • 删除文件
  • 使用带空格的正则表达式获取文件:inum
  • 使用find . -regex '.* .*' -deletexargs
  • 在运行find . -type -f -print 0命令之前,创建一个函数来转义文件名\的所有空格