2012-04-17 67 views
3

我正在嘗試將我的照片排序到縱向和橫向。我想出了一個打印JPEG文件的大小尺寸的命令:如果我是用它在bash腳本,將所有的風景圖片到另一個文件夾我希望它是這樣的Bash解析輸出到變量

identify -format '%w %h\n' 1234.jpg 
1067 1600 

#!/bin/bash 
# loop through file (this is psuedo code!!) 
for f in ~/pictures/ 
do 
# Get the dimensions (this is the bit I have an issue with) 
identify -format '%w %h\n' $f | awk # how do I get the width and height? 
if $width > $hieght 
    mv ~/pictures/$f ~/pictures/landscape/$f 
fi 
done 

一直在看awk手冊頁,但我似乎無法找到語法。

回答

3

你不需要AWK。做這樣的事情:

identify -format '%w %h\n' $f | while read width height 
do 
    if [[ $width -gt $height ]] 
    then 
     mv ~/pictures/$f ~/pictures/landscape/$f 
    fi 
done 
+0

這就是機票,當再次讀awk的人時,它確實發生在我身上,可能有更好的辦法。謝謝。 – Ne0 2012-04-17 08:48:04

+0

@ Ne0:應該在每個出現的地方引用變量'$ f',因爲圖像文件名通常包含空格。既然你使用的是Bash,你應該使用它來進行整數比較:'if((width> height))'。請注意,雖然在這種情況下它可以工作,但將命令輸入到'while'會創建一個子shell,這意味着當循環退出時,設置的任何變量值都將丟失。在這種情況下,使用進程替換:'while ... done <<(identify ...)',並且變量值將在循環完成後可用。 – 2012-04-17 13:27:17

+0

什麼是while循環? 「識別」似乎沒有輸出多行。 – Kaz 2012-04-17 15:08:14

4

您可以使用array

# WxH is a array which contains (W, H) 
WxH=($(identify -format '%w %h\n' $f)) 
width=${WxH[0]} 
height=${WxH[1]} 
+0

哇,我不知道bash的:) – slipset 2012-04-17 08:28:01

+0

的東西,不要把美元符號在作業的左側。 – 2012-04-17 13:21:46

+0

固定爲你 – 2012-04-17 15:00:02

1
format=`identify -format '%w %h\n' $f`; 
height=`echo $format | awk '{print $1}'`; 
width=`echo $format | awk '{print $2}'`; 
-2

Goofballs,現在對於「衛生署,明顯」:

# use the identify format string to print variable assignments and eval 
eval $(identify -format 'width=%w; height=%h' $f)