我试图用空行分割myfile.txt作为分隔符,并将每个值存储在数组中。
fruit=mango, lime, orange,grape
car=nissan,
ford,
toyota,
honda
country=russia, england, ireland,
usa,
mexico,australia
colors=green, orange, purple, white,
yellow
我写了以下脚本
while IFS='\n' read -r line || [[ -n "$line" ]]; do
if [[ $line != "" ]]; then
arr+=("$line")
echo "File Content : $line"
fi
done < myfile.txt
我遇到的问题是针对这样的国家
File Content : country=russia, england, ireland
File Content : usa,
File Content : mexico,australia
我希望将其打印为
File Content : country=russia, england, ireland, usa,mexico,australia
有人可以帮我调整我的脚本吗?
提前致谢
declare -A content=( ) # create an empty associative array, "content"
curr_key= # and a blank "key" variable
while read -r line; do
[[ $line ]] || { curr_key=; continue; } # on a blank input line, reset the key
if [[ $line = *=* ]]; then # if we have an equal sign...
curr_key=${line%%=*} # ...then use what's left of it as the key
content[$curr_key]=${line#*=} # ...and what's right of it as initial value
elif [[ $curr_key ]]; then # on a non-blank line with no equal sign...
content[$curr_key]+=$line # ...append the current line to the current value
fi
done
declare -p content # print what we've found
给定您的输入文件,并使用bash 4.0或更高版本运行,以上内容将作为输出显示(仅针对可读格式进行了修改):
declare -A content='([car]="nissan,ford,toyota,honda"
[colors]="green, orange, purple, white,yellow"
[fruit]="mango, lime, orange,grape"
[country]="russia, england, ireland,usa,mexico,australia" )'
如果然后要遍历类别的成员,则可以按照以下步骤进行:
IFS=', ' read -r -a cars <<<"${content[car]}"
for car in "${cars[@]}"; do
echo "Found a car: $car"
done
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句