2015-11-06 76 views
3

我想用空行分隔myfile.txt作为分隔符并将每个值存储在数组中。在shell脚本中使用空行空间拆分文件并存储在数组中

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 

你能帮我调整我的吗?脚本。

在此先感谢

+1

既然你说“数组”,这应该被标记不只是“壳”,但是对于具有数组支持的特定壳(如bash)。基准POSIX sh不支持数组。 –

回答

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 
+0

我修改完成的跑到这个<$ fileLocation 回声$ {#内容[@]} 回声$ {内容[@]} 这里是输出我 绿,橙,紫,白,黄 我使用bash版本4.2 – Mowgli

+0

它没有在我的mac中工作,但在linux机器上工作正常。 – Mowgli

+0

MacOS不提供bash 4.2 - 如果您使用的是macports的副本,请确保您修改了shebang,直接指向它或使用'#!/ usr/bin/env bash'首先有4.2)。 –

1

我建议我们可以选择一种解决方案来解决这种格式,并且有一个更简单的逻辑来处理线条。

$ 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"以及加入之间的空行。

相关问题