使用Bash脚本在子文件夹中执行ImageMagick转换 [英] Execute ImageMagick convert in subfolders with Bash script
问题描述
我有多个jpeg系列。每个系列都在自己的文件夹中。我希望将每个系列转换为单个pdf。我还希望pdf与它所在的文件夹具有相同的名称。
I have multiple series of jpegs. Each series is in its own folder. I wish to convert each series into a single pdf. I would further like the pdf to have the same name as the folder it is in.
要在每个文件夹的命令行中执行此操作,我可以使用以下命令:
To do this on the command line in each folder I can use the following command:
convert *.jpg `echo ${PWD##*/}`.pdf
我想从顶级文件夹中使用bash脚本执行此操作。
I would like to do it from the top level folder with a bash script.
推荐答案
您可能希望使用 find
:
find . -type d -exec bash -c 'cd "$0" || exit; shopt -s nullglob; f=( *.jpg ); ((${#f[@]})) && echo convert "${f[@]}" "${PWD##*/}.pdf"' {} \;
这将递归到每个子目录中,并且每次执行Bash命令:
This will recurse into each subdirectory and for each execute the Bash commands:
cd "$0" || exit
shopt -s nullglob
f=( *.jpg )
((${#f[@]})) && echo convert "${f[@]}" "${PWD##*/}.pdf"
-
$ 0
将扩展为给予Bash的参数,即找到的目录
。退出
在这里作为安全措施,以防在那里cd
是不可能的:你不想随机在这种情况下执行的命令。 -
shopt -s nullglob
:如果没有匹配,则globs扩展为空。如果存在没有以.jpg
结尾的文件名的子目录,则非常有用。 - 构建数组
f $当前目录中所有文件名的c $ c>,文件名以
.jpg
结尾。如果没有这样的文件,这个数组是空的(感谢nullglob
shell选项)。 -
如果数组
f
非空,执行命令:- The
$0
will expand to the argument given to Bash, i.e., the directory found byfind
. Theexit
is here as a security in case it's impossible tocd
in there: you don't want to have random commands executed in this case. shopt -s nullglob
: if there are no matches, the globs expand to nothing. Useful if there are subdirectories with no filenames ending in.jpg
.- build an array
f
of all the filenames in current directory with a filename ending in.jpg
. This array is empty if there are no such files (thanks to thenullglob
shell option). If the array
f
is non-empty, execute the command:echo convert "${f[@]}" "${PWD##*/}.pdf"
(by顺便说一下,你的
echo $ {PWD ## * /}。pdf
错误,见下文。)(by the way, your
echo ${PWD##*/}.pdf
is wrong, see below).我在
转换$ c前面放了
echo
$ c>,以便实际上不执行任何操作;命令显示在标准输出上,以便您可视地检查一切是否按预期工作。如果是这种情况,只需删除echo
!你在评论中问道:为什么你说下面这行是错的?
You asked in a comment: why do you say the following line is wrong?
convert *.jpg `echo ${PWD##*/}`.pdf
你甚至说因为它有效。 工作和是正确的在计算机科学中并不相同。 it works 句子应该以完整的下列形式理解:它可以工作直到失败。失败的最明显的情况是目录名称是否包含空格:假设目录名称为
hello world
然后转换将显示hello
作为参数,以及world.pdf
作为最后一个参数。很可能不是你想要的。此外,以下是正确的(更短更容易理解):you even say since it worked. To work and to be correct are not equal in computer science. The it works sentence should be understood in the full following form: it works until it fails. The most obvious case where this fails is if the directory name contains spaces: imagine a directory name of
hello world
then convert will seehello
as an argument on its own, andworld.pdf
as the last argument. Very likely not what you want. Besides, the following is correct (and shorter and easier to understand):convert *.jpg "${PWD##*/}.pdf"
这篇关于使用Bash脚本在子文件夹中执行ImageMagick转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- The