在 shell 脚本中使用空行空间分割文件并存储在数组中

Mow*_*gli 5 shell

我试图用空行作为分隔符分割 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
Run Code Online (Sandbox Code Playgroud)

我写了以下脚本

while IFS='\n' read -r line || [[ -n "$line" ]]; do
    if [[ $line != "" ]]; then
        arr+=("$line")
        echo "File Content : $line"
    fi
done < myfile.txt
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是对于国家来说它是这样的

File Content : country=russia, england, ireland
File Content : usa,
File Content : mexico,australia
Run Code Online (Sandbox Code Playgroud)

我希望将其打印为

File Content : country=russia, england, ireland, usa,mexico,australia
Run Code Online (Sandbox Code Playgroud)

你能帮我调整一下我的剧本吗?

提前致谢

Cha*_*ffy 2

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
Run Code Online (Sandbox Code Playgroud)

给定您的输入文件,并使用 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" )'
Run Code Online (Sandbox Code Playgroud)

如果您随后想要迭代某个类别的成员,可以按如下方式执行操作:

IFS=', ' read -r -a cars <<<"${content[car]}"
for car in "${cars[@]}"; do
  echo "Found a car: $car"
done
Run Code Online (Sandbox Code Playgroud)