0

我正在处理一包图片,“文件”从中返回以下内容:

$ file pic.jpg
pic.jpg: JPEG image data, JFIF standard 1.01, resolution (DPI), density 96x96, segment length 16, baseline, precision 8, 231x288, frames 3
$ file pic.jpg | cut -d',' -f8 | tail -c+2
231x288

因此,在继续裁剪之前,我使用内置的“读取”在两个变量中选择尺寸。

但有些事情让我无法理解。为什么这个构造不起作用...

$ ( file pic.jpg | cut -d',' -f8 | tail -c+2 | IFS=x read width height ; echo w:$width h:$height; )
w: h:

...当这个结构在工作时?

$ ( IFS=x read width height <<< $(file pic.jpg | cut -d',' -f8 | tail -c+2) ; echo w:$width h:$height; )
w:231 h:288

总而言之,为什么我不能在这种情况下使用带有内置“读取”的管道?

4

3 回答 3

3

在 bash 中,管道中的命令在子 shell 中运行(参见手册中管道的最后一段)。当子shell 退出时,您在子shell 中声明的任何变量都将消失。

您可以使用{ }分组构造将read和保持echo在同一个子shell中:

file pic.jpg | cut -d',' -f8 | tail -c+2 | { IFS=x read width height ; echo w:$width h:$height; }

这就是 here-string 有用的原因:它在当前readshell 中运行命令,因此变量在下一个命令中可用。

于 2015-03-30T16:00:11.103 回答
1

您可以使用ImageMagick 中的标识并执行

$ identify -format 'w=%[w]; h=%[h]' file.jpg

注意使用,=所以;你可以做

$ eval $(identify -format 'w=%[w]; h=%[h]' file.jpg)

在你的shell中设置变量

于 2015-03-30T16:58:21.837 回答
0

实际上,当您使用bash时,还有一种更简单的方法,它只需要一行,没有evals,没有cuts 和没有tails:

read w h < <(identify -format "%w %h" file.jpg)

当您想要提取许多参数时,它真的会发挥自己的作用,例如高度、宽度、平均值、标准差、色彩空间和唯一颜色的数量等。一次调用即可:

read w h m s c u < <(identify -format "%w %h %[mean] %[standard-deviation] %[colorspace] %k" file.jpg)
于 2015-03-31T11:02:04.867 回答