[英]How to add values from an array in bash with a for loop
My goal is to automate the annotation feature in convert (Imagemagick) for myself. 我的目标是为自己自动化convert(Imagemagick)中的注释功能。 Running the script in a folder with some images: I try to read a text file with the annotation titles, each on a new line.
在包含一些图像的文件夹中运行脚本:我尝试读取带有注释标题的文本文件,每行都有一个新行。 Then read the file into an array.
然后将文件读入数组。 (maybe there is a better way?)
(也许有更好的方法?)
I am not able to understand how to add each value of the array and loop through all the images in the folder. 我不明白如何添加数组的每个值并循环浏览文件夹中的所有图像。
Here is the script so far: 到目前为止,这是脚本:
#!/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
Here is a solution: 这是一个解决方案:
# 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.