将字符串拆分为具有多个分隔符shell的数组

时间:2015-03-11 08:53:33

标签: arrays bash delimiter string-split

我有一个文本文件,内容格式为......

File=/opt/mgtservices/probes/logs is_SS_File=no is_Log=yes Output_File=probes_logs

这可以有大约1k条记录。我正在从文件中逐行阅读。

while read -r line
do
  if [ $SS_SERVER -eq 0 ]
  then
    arr=$(echo "$line" | tr ' =' "\n")
    echo $arr[1]
    #do something
  elif [[ $SS_SERVER -eq 1 && "$line" =~ "is_SS_File=\"no\"" ]]
  then
    #do something else
  fi
done < "$filename"

我期待arr应该是一个数组,这样我就可以得到输出:

arr[1]=File
arr[2]=/opt/mgtservices/probes/logs
arr[3]=is_SS_File
and so on...

我没有到这里来。 arr [1]给了我完整的行,没有&#34; =&#34; 我想使用2个分隔符&#34; space&#34;和&#34; =&#34;。

1 个答案:

答案 0 :(得分:1)

根据您要完成的任务,尝试以下方法:

tr ' =' '\n ' <"$file" |
while read keyword value; do
    : you get one keyword and its value at a time now
done

或者

while IFS=' =' read -a arr; do
    : arr[0] is first keyword
    : arr[1] is its value
    : arr[2] is second keyword
    : etc
done <"$file"
相关问题