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

在shell脚本中使用空行空间分割文件并存储在数组中,shell,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 我写了下面的脚本 while IFS='\n' read -r line |

我正在尝试拆分一个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, 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或更新版本运行,以上内容将作为输出打印(仅针对可读格式进行修改):

然后,如果要迭代类别的成员,可以按如下方式执行:

IFS=', ' read -r -a cars <<<"${content[car]}"
for car in "${cars[@]}"; do
  echo "Found a car: $car"
done

IFS=”,“read-r-acars我建议另一种解决方案来修复格式,并使用更简单的逻辑来处理行

$ awk -v RS= '{gsub(",\n",",")}1' file
结果

fruit=mango, lime, orange,grape
car=nissan,ford,toyota,honda
country=russia, england, ireland,usa,mexico,australia
colors=green, orange, purple, white,yellow

您也可以通过添加选项
-v ORS=“\n\n”
在这两者之间添加空行。

因为您使用的是“arrays”,所以不仅应该标记为“shell”,还应该标记为具有数组支持的特定shell(如bash)。基线POSIX sh不支持数组。我通过修改done<$fileLocation echo${content[@]}echo${content[@]}来运行它。这里是我得到的输出1绿色、橙色、紫色、白色、黄色我使用的是bash版本4.2,它在我的mac上不工作,但在linux机器上工作正常。MacOS不提供bash 4.2--如果您使用的是macports的副本,确保您修改了shebang,或者直接指向它,或者使用
#/usr/bin/env bash
(路径优先为4.2)。顺便说一句,引号很重要
@Moogly,…仅获得
绿色、橙色、紫色、白色、黄色
作为输出意味着您的bash没有关联数组,即它是3.x而不是4.x,因此它不断覆盖第一个数组项(索引0,因为当“水果”或“汽车”或“国家”或“颜色”时在数值上下文中使用,就像非关联数组索引一样,除非有一个由这些名称组成的带有数值的变量,否则它的计算结果为0。
$ awk -v RS= '{gsub(",\n",",")}1' file
fruit=mango, lime, orange,grape
car=nissan,ford,toyota,honda
country=russia, england, ireland,usa,mexico,australia
colors=green, orange, purple, white,yellow