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

时间:2012-11-29 04:21:29

标签: linux bash shell

我在目录中有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。

1 个答案:

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