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

时间:2015-11-06 20:05:05

标签: 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 || [[ -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

你能帮我调整一下我的剧本。

提前致谢

2 个答案:

答案 0 :(得分: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

给定您的输入文件,并使用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

答案 1 :(得分:2)

我建议使用另一种解决方案来修复格式并使用更简单的逻辑来处理行。

$ 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"来添加空行。