【问题标题】:How to add values from an array in bash with a for loop如何使用for循环从bash中的数组添加值
【发布时间】:2014-10-19 14:42:37
【问题描述】:

我的目标是为我自己在 convert (Imagemagick) 中自动化注释功能。在包含一些图像的文件夹中运行脚本:我尝试读取带有注释标题的文本文件,每个文件都在一个新行上。 然后将文件读入数组。 (也许有更好的方法?)

我无法理解如何添加数组的每个值并遍历文件夹中的所有图像。

这是目前为止的脚本:

#!/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

【问题讨论】:

    标签: arrays bash nested-loops imagemagick-convert


    【解决方案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
    

    【讨论】:

    • 谢谢 Edouard,这样一个简单的解决方案非常有用。
    猜你喜欢
    • 2019-11-29
    • 1970-01-01
    • 1970-01-01
    • 2019-04-02
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 2020-01-25
    相关资源
    最近更新 更多