2014-10-19 51 views
1

我的目標是在轉換(ImageMagick的)爲自己自動註釋功能。一些圖像的文件夾中運行腳本:我嘗試閱讀的文本文件註釋標題,每一個新行。 然後文件讀入到一個數組。 (也許有更好的辦法?)如何從一個數組在bash與添加值環

我無法理解如何通過該文件夾中的所有圖像添加數組和循環的每個值。

這裏是腳本至今:

#!/usr/bin/bash 

## content of file.txt 
sample 1 
sample 2 
sample 3 
sample 4 
sample 5 
sample 6 
sample 7 
sample 8 
sample 9 

## Read from a file into an array, print the array 
array=() 

# Read the file in parameter and fill the array named "array" 
getArray() { 
    i=0 
    while read line # Read a line 
    do 
    array[i]=$line # Put it into the array 
    i=$(($i + 1)) 
    done < $1 
} 

getArray "file.txt" 

## Here my problems start 

for f in *.jpg; do fn=${f%.*}; 

    for e in "${array[@]}";do 

    convert ${fn}.jpg -fill white -gravity South -pointsize 32 -annotate +0+5 "$e" ${fn}_annotated.jpg ;done 

done 

回答

1

這裏是一個解決方案:

# Store the whole file in an array 
readarray array < "file.txt" || exit 1 

i=0 
for f in *.jpg ; do 
    fn=${f%.*} 
    title=${array[i++]} # in array[] bash performs arithmetic expansion 

    convert "$fn.jpg" -fill white -gravity South -pointsize 32 \ 
     -annotate +0+5 "$title" "${fn}_annotated.jpg" 
done 
+0

謝謝愛德華,它的工作原理非常好的這樣一個簡單的解決方案。 – user79491 2014-10-19 17:13:12

+0

不客氣! – 2014-10-22 18:13:34