linux - 分别合并来自不同子目录的 jpg 并将它们保存到一个文件夹中

标签 linux bash shell

我在一个目录中有从 1 到 700 命名的文件夹(中间有很多缺失的数字)。在每个文件夹中都有需要合并并转换为pdf 文件的jpg 文件。每个文件夹中的图像必须创建为单独的 pdf 文件。为了合并和转换图像,我使用了以下脚本:

cd subfolder1
for i in *.jpg; do num=`expr match "$i" '\([0-9]\+\).*'`;
padded=`printf "%03d" $num`; mv -v "$i" "${i/$num/$padded}"; done
FILES=$( find . -type f -name "*jpg" | cut -d/ -f 2)
mkdir temp && cd temp 
for file in $FILES; do 
    BASE=$(echo $file | sed 's/.jpg//g');
    convert ../$BASE.jpg $BASE.pdf; 
    done && 
pdftk *pdf cat output ../../pdffolder/subfolder1.pdf && 
cd .. 
rm -rf temp

pdffolder 是我需要所有 pdf 文件所在的目录。是否有类似 for directory in a 之类的东西或我可以用于此目的的东西? pdf 文件也必须与子文件夹同名。运行平台为Linux。

最佳答案

要获取目录列表并循环遍历它们,您可以将 findfor 循环结合使用:

for subdir in $(find path/to/parent/dir -maxdepth 1 -type d); do
        # Do stuff with $subdir i.e:
        echo $subdir
done

这里的find仅限于-type d的目录,-maxdepth 1只会给出初始的子目录,不会给出子目录子目录的目录。

将您的初始代码放入此循环中:

START_DIR=$(pwd)
# Loop over all directories
for subdir in $(find path/to/parent/dir -mathdepth 1 -type d); do
      # Get the base name, for the pdf naming
      subdir_base=$(basedir $subdir);

      cd subdir;

      for i in *.jpg; do 
          num=`expr match "$i" '\([0-9]\+\).*'`;
          padded=`printf "%03d" $num`; mv -v "$i" "${i/$num/$padded}";
      done

      FILES=$( find . -type f -name "*jpg" | cut -d/ -f 2)
      mkdir temp && cd temp 

      for file in $FILES; do 
           BASE=$(echo $file | sed 's/.jpg//g');
           convert ../$BASE.jpg $BASE.pdf; 
      done && 
      pdftk *pdf cat output ../../pdffolder/$subdir_base.pdf && 
      cd ..
      rm -rf temp
      cd $START_DIR;
 done;

关于linux - 分别合并来自不同子目录的 jpg 并将它们保存到一个文件夹中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13618784/

相关文章:

linux - 在 shell 脚本中格式化文本

c++ - 如何将 MongoDB 与 Qt C++ 连接起来?

BASH 使用双变量 $ - 错误替换

regex - 如何匹配单行字符串上最后一次出现的模式

java - ANTLR 警告 : TestRig moved to org. antlr.v4.gui.TestRig

linux - 每天监视文件夹的 Shell 脚本,如果该文件夹上未生成新文件,将发送邮件警报

linux - 可以让子进程在新终端上运行吗

php - 通过不同服务器的 FTP PHP

bash - 是否可以在 bash 中复制 vim 的 `zz` 的效果?

bash - bash 中的哈希集或关联数组