1

所以我有一些文件夹

|-Folder1
||-SubFolder1
||-SubFolder2
|-Folder2
||-SubFolder3
||-SubFolder4

每个子文件夹包含几个 jpg 我想压缩到根文件夹...我有点卡在“如何进入每个文件夹”上

这是我的代码:

find ./ -type f -name '*.jpg' | while IFS= read i 
do
   foldName=${PWD##*/}
    zip ../../foldName *
done

更好的是存储 FolderName+SubFolderName 并将其作为名称提供给 zip 命令...

4

4 回答 4

1

压缩 JPEG(用于压缩)通常是浪费精力

首先,尝试压缩已压缩的格式(如 JPEG 文件)通常是浪费时间,有时会导致存档比原始文件大。但是,为了方便将一堆文件放在一个包中,这样做有时很有用。

只是要记住的事情。YMMV。

使用 Find 的-execdir标志

您需要的是find实用程序的-execdir标志。GNU find 手册页说:

   -execdir command {} +
          Like -exec, but the specified command is run from the  subdirec‐
          tory  containing  the  matched  file,  which is not normally the
          directory in which you started find.

例如,给定以下测试语料库:

cd /tmp
mkdir -p foo/bar/baz
touch foo/bar/1.jpg
touch foo/bar/baz/2.jpg

您可以使用 find 压缩整个文件集,同时通过一次调用排除路径信息。例如:

find /tmp/foo -name \*jpg -execdir zip /tmp/my.zip {} +

使用 Zip 的--junk-paths标志

许多系统上的 zip 实用程序都支持--junk-paths标志。zip的手册页说:

  --junk-paths
          Store just the name of a saved file (junk the path), and do  not
          store  directory names.

因此,如果您的 find 实用程序不支持-execdir,但您确实有一个支持垃圾路径的 zip,您可以这样做:

find /tmp/foo -name \*jpg -print0 | xargs -0 zip --junk-paths /tmp/my.zip
于 2013-05-09T18:18:27.803 回答
0

好的,终于明白了!

find ./* -name \*.zip -type f -print0 | xargs -0 rm -rf

find ./*/* -type d | while read line; do
  #printf '%s\n' "$line"
  zip --junk-paths ./"$line" "$line"/*.jpg
done

find . -name \*.zip -type f -mindepth 2 -exec mv -- '{}' . \;

在第一行中,我只是删除了所有 .zip 文件,

然后我全部压缩并在最后一行将所有压缩文件移动到根目录!

谢谢大家的帮助!

于 2013-05-09T20:27:08.940 回答
0

您可以使用dirname获取它所在的文件/目录的目录名称。您还可以简化find命令,使用-type d. 然后你应该使用basename只获取子目录的名称:

find ./*/* -type d | while read line; do
  zip  --junk-paths "$(basename $line)" $line/*.jpg
done 

解释

  • find ./*/* -type d 将打印出位于其中的所有目录,./*/* 这将导致位于当前目录中的目录的所有子目录
  • while read line从流中读取每一行并将其存储在变量“line”中。因此 $line 将是子目录的相对路径,例如“Folder1/Subdir2”
  • "$(basename $line)"返回子目录的唯一名称,例如“Subdir2”
  • 更新:如果您不希望将直接路径存储在 zip 文件中,请将 --junk-paths 添加到 zip 命令
于 2013-05-07T19:43:25.577 回答
0

所以稍微检查一下,我终于得到了一些工作:

find ./*/* -type d | while read line; do
  #printf '%s\n' "$line"
  zip ./"$line" "$line"/*.jpg
done

但这会创建联合国档案,其中包含:

Subfolder.zip
Folder
|-Subfolder
||-File1.jpg
||-File2.jpg
||-File3.jpg

相反,我像这样折叠:

Subfolder.zip
|-File1.jpg
|-File2.jpg
|-File3.jpg

所以我尝试在不同的组合中使用 basename 和 dirname ......总是遇到一些错误......并且只是为了学习如何:如果我希望在与“文件夹”相同的根目录中创建新存档怎么办?

于 2013-05-09T17:41:39.607 回答