我不确定是否理解...
你需要这样的东西吗?
array=()
# Read the file in parameter and fill the array named "array"
getArray() {
i=0
while read line
do
array[i]=$line
i=$(($i + 1))
done < $1
}
getArray "file.txt"
for line in "${array[@]}"
do
# some actions using $line
done
编辑 :
要回答您的问题,是的,可以将数据 grep 到一个数组中并将其推送到另一个数组中。可能有更好的方法来做到这一点,但这有效:
array2=()
# Split the string in parameter and push the values into the array
pushIntoArray() {
i=0
for element in $1
do
array2[i]=$element
i=$(($i + 1))
done
}
array1=("foo" "bar" "baz")
# Build a string of the elements into the array separated by '\n' and redirect the ouput to grep.
str=`printf "%s\n" "${array1[@]}" | grep "a"`
pushIntoArray "$str"
printf "%s\n" "${array2[@]}" # Display array2 line by line
此片段的输出:
$ ./grep_array.sh
bar
baz