【问题标题】:Merge jpg from diffrerent subdirectories individually and save them to a single folder分别合并来自不同子目录的 jpg 并将它们保存到单个文件夹
【发布时间】:2012-11-17 02:43:26
【问题描述】:

我在一个目录中有从 1 到 700 的文件夹(中间有很多缺失的数字)。在每个文件夹中都有jpg 文件需要合并并转换为pdf 文件。每个文件夹中的图像必须创建为单独的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。

【问题讨论】:

    标签: linux bash shell


    【解决方案1】:

    要获取目录列表并循环遍历它们,您可以将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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-04
      • 2018-07-20
      • 1970-01-01
      相关资源
      最近更新 更多