【问题标题】:How to compress files larger than a certain size in a directory?如何压缩目录中大于一定大小的文件?
【发布时间】:2017-02-07 18:39:38
【问题描述】:

此代码背后的想法是查找大于 1KB(或 1000 字节)的目录中的所有文件,压缩它们,然后将它们从原始目录中删除。我能够找出两个单独的命令,但不确定如何将第一个命令的输出链接到第二个命令(如果有意义的话)?谁能指出我正确的方向?

# Initialize variables
dir=~/Test 

# Change directory to $DIRECTORY
cd "$dir"

# Find all files in the current directory that are larger than 1000 bytes (1KB).
find . -maxdepth 1 -type f -size +1000c | zip -mT backup

【问题讨论】:

标签: linux bash shell scripting


【解决方案1】:

使用-exec 选项而不是尝试通过管道传递下一个命令:

find . -maxdepth 1 -type f -size +1000c -exec zip -mT backup {} \;

将创建一个包含匹配文件的 zip 存档。

【讨论】:

  • 查看 find 的手册页,我应该意识到这是一个选项。谢谢!我现在收到一个错误,find: paths must precede expression- 我的路径应该只是 . (当前目录),它肯定在表达式之前,所以关于它为什么会出现这个错误的任何想法?
  • 听起来好像发生了一些shell扩展,通常如果没有正确引用某些内容(如路径、变量等),则会发生此错误;其他原因也存在,但需要更具体的细节......
【解决方案2】:

我之前提供了一个存根,但我决定充实脚本。这仍然无法处理异常情况,例如包含通配符的文件名。

#!/usr/bin/bash
# the following line handles filenames with spaces
IFS='
'
backupfilename=backup;

for file in $(find . -maxdepth 1 -type f -size +1000c)
do
  if zip ${backupfilename} -u "${file}" # test that zip succeeded
  then
     echo "added file ${file} to zip archive ${backupfilename}" 1>&2;
     # add your remove command here; remember to use quotes "${filename}"
     echo "file ${file} has been deleted" 1>&2;
  fi
done

我唯一遗漏的是删除命令。您应该自己解决这个问题并仔细测试,以确保您不会意外删除您不想删除的文件。

【讨论】:

  • 这样做,您还可以在删除应该添加到存档的文件之前测试存档命令是否成功。
  • 如果目录中有任何带有空格或通配符的文件,这将失败 - 因为分词和通配符。
  • 要处理带空格的文件名,请在 for 循环之前添加行 ... IFS=' ' ...。那就是说只使用新行来分隔文件名。我将不得不查看带有通配符的文件名。
  • set -f 可以抑制通配。
  • 我上一条评论的格式不正确:新行已被删除。它应该是 IFS=''。在某些 shell 中,您还可以使用 IFS='\n'。
【解决方案3】:

使用 xargs 将 find 输出中的每一行作为 zip 参数传递:

find . -maxdepth 1 -type f -size +1000c | xargs -I f zip -mT backup f

你也可以使用while循环来做同样的事情:

find . -maxdepth 1 -type f -size +1000c | while read f ; do zip -mT backup $f ; done

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多