嗨,我必须将文件捕获到数组中,然后将该数组传递到while循环中。
我只是不想在下面的while循环中执行我的脚本,因为这需要很长时间...
while read line; do
some actions...
done < file.txt
我的服务器有8 GB内存,其中6 GB始终可用。因此,请告诉我天气是个好主意,将大小为100 MB的文件捕获到内存(数组)中并对其执行grep,sed,awk等操作。
如果是这样,请让我知道如何将文件捕获到数组中。
如果不能的话,建议我另一种提高性能的方法。
我不确定要了解...
你需要这样的东西吗?
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句