我在目录中有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。
答案 0 :(得分:1)
要获取目录列表并循环遍历它们,您可以将find
与for
循环结合使用:
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;