Shell 脚本输出存入字典:使用关联数组存储结果
在 shell 脚本中,可以使用关联数组(也就是字典)来存储输出结果。下面是一个例子:
#!/bin/bash
declare -A result # 声明关联数组
# 循环读取文件中的每一行并处理
while read line; do
# 在每一行中查找关键字,并将匹配结果存入字典
if [[ $line =~ 'error' ]]; then
result['errors']=$(( ${result['errors']} + 1 ))
elif [[ $line =~ 'warning' ]]; then
result['warnings']=$(( ${result['warnings']} + 1 ))
fi
done < logfile.txt
# 输出字典中的结果
echo 'Errors: ${result['errors']}'
echo 'Warnings: ${result['warnings']}'
在上面的例子中,我们首先使用declare -A命令声明了一个关联数组result。然后,我们使用while read循环读取一个名为logfile.txt的文件中的每一行,并使用正则表达式匹配关键字。如果匹配到了'error'或'warning',就将对应的字典值加1。最后,我们输出字典中的结果。
原文地址: https://www.cveoy.top/t/topic/nyFh 著作权归作者所有。请勿转载和采集!