如何在目录中压缩大于特定大小的文件?

时间:2017-02-07 18:39:39

标签: linux bash shell scripting

此代码背后的想法是查找大于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

3 个答案:

答案 0 :(得分:4)

使用-exec选项,而不是尝试管道下一个命令:

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

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

答案 1 :(得分: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

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

答案 2 :(得分:0)

使用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