我有一个包含文件列表的文件:
02 of Clubs.eps
02 of Diamonds.eps
02 of Hearts.eps
02 of Spades.eps
...
我正在尝试将它们批量转换为多种尺寸的 png 格式。我用来执行此操作的脚本是:
while read -r line
do
for i in 80 35 200
do
convert $(sed 's/ /\\ /g' <<< Cards/${line}) -size ${i}x${i} ../img/card/$(basename $(tr ' ' '_' <<< ${line} | tr '[A-Z]' '[a-z]') .eps)_${i}.png;
done
done < card_list.txt
但是,这不起作用,显然是试图拆分每个单词,导致以下错误输出:
convert: unable to open image `Cards/02\': No such file or directory @ error/blob.c/OpenBlob/2514.
convert: no decode delegate for this image format `Cards/02\' @ error/constitute.c/ReadImage/532.
convert: unable to open image `of\': No such file or directory @ error/blob.c/OpenBlob/2514.
convert: no decode delegate for this image format `of\' @ error/constitute.c/ReadImage/532.
convert: unable to open image `Clubs.eps': No such file or directory @ error/blob.c/OpenBlob/2514.
如果我将转换更改为 echo,结果看起来是正确的,如果我复制一行并在 shell 中自己运行它,则效果很好:
convert Cards/02\ of\ Clubs.eps -size 80x80 ../img/card/02_of_clubs_80.png
convert Cards/02\ of\ Clubs.eps -size 35x35 ../img/card/02_of_clubs_35.png
convert Cards/02\ of\ Clubs.eps -size 200x200 ../img/card/02_of_clubs_200.png
convert Cards/02\ of\ Diamonds.eps -size 80x80 ../img/card/02_of_diamonds_80.png
convert Cards/02\ of\ Diamonds.eps -size 35x35 ../img/card/02_of_diamonds_35.png
convert Cards/02\ of\ Diamonds.eps -size 200x200 ../img/card/02_of_diamonds_200.png
convert Cards/02\ of\ Hearts.eps -size 80x80 ../img/card/02_of_hearts_80.png
convert Cards/02\ of\ Hearts.eps -size 35x35 ../img/card/02_of_hearts_35.png
convert Cards/02\ of\ Hearts.eps -size 200x200 ../img/card/02_of_hearts_200.png
convert Cards/02\ of\ Spades.eps -size 80x80 ../img/card/02_of_spades_80.png
更新:
仅添加引号(见下文)与上面的结果相同,我一直在使用 sed 添加反斜杠
convert '"'Cards/${line}'"' -size ${i}x${i} ../img/card/$(basename $(tr ' ' '_' <<< ${line} | tr '[A-Z]' '[a-z]') .eps)_${i}.png;
我尝试过双引号和单引号
最佳答案
Shell 可以很好地处理行分割,并使用变量使代码可读 - 此处避免水平滚动条...
while read -r line
do
for i in 80 35 200
do
epsfile="Cards/$line"
pngbase=$(basename "$line" .eps | tr ' A-Z' '_a-z')
pngfile="../img/card/${pngbase}_${i}.png"
convert "$epsfile" -size ${i}x${i} "$pngfile"
done
done < card_list.txt
如果您必须处理包含空格的文件名,则在将它们传递给命令时需要将名称括在双引号中。所有文件操作都压缩成一行的复杂代码几乎无法阅读。您可以在一个命令中完成整个音译,如上所示,这也简化了事情。
尽管 80 个字符不是硬性限制,但仍值得将其保留为粗略限制,因为如果行太长,则可能不可读,并且代码必须可读才能维护。
关于bash - 在 bash 脚本中运行带有空格字符的命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4642734/