Bash追加到数组元素的末尾

时间:2017-10-19 08:52:22

标签: arrays bash

我有一个命令,当我运行它时,它输出一个看起来像的表;

Id        Name                                  File                                  OS          Version   Annotation   
10     MICKEY     [MICKEY_01_001] MICKEY/MICKEY.vmx       windows8Server64Guest   vmx-08    
13     DONALD     [DONALD_01_001] DONALD/DONALD.vmx       windows7Server64Guest   vmx-10
2      GOOFY      [GOOFY_01_001] GOOFY/GOOFY.vmx       windows9Server64Guest   vmx-09

然后我将表存储在数组调用TABLE中并列出TABLE数组,代码如下所示;

readarray -t TABLE <<< "$(command)"
IFS='|'
for i in "${TABLE[@]}"
do
  echo $I
done

如何附加到每个数组元素的末尾?我希望表格如下:

Id        Name                                  File                                  OS          Version   Annotation    
10     MICKEY     [MICKEY_01_001] MICKEY/MICKEY.vmx       windows8Server64Guest   vmx-08     ON    
13     DONALD     [DONALD_01_001] DONALD/DONALD.vmx       windows7Server64Guest   vmx-10.    OFF    
2      GOOFY      [GOOFY_01_001] GOOFY/GOOFY.vmx       windows9Server64Guest   vmx-09.    ON

2 个答案:

答案 0 :(得分:0)

命令"$(command)"有什么作用?我们应该假设,输出的一行=一个字符串=数组的一个元素?如果是这样,那么这应该适合你:

readarray -t TABLE <<< "$(command)"
IFS='|'
for i in "${TABLE[@]}"
do
  if <condition_for_on_met>; then
     echo "$i ON"
  elif <condition_for_off_met>;then
     echo  "$i OFF"
  else
     echo  "$i"
  fi
done

但这是一个普遍的答案。您可以通过向我们展示您的输入是什么以及在打印之前如何处理来改进您的问题。

答案 1 :(得分:0)

如果要在数组中附加ON或OFF

readarray -t TABLE <<< "$(command)"
#IFS='|' why ?
for ((i=1;i<"${#TABLE[@]}";i++))
# start i=1 to preserve header
do
  # condition to ON or OFF
  [ "${a:=OFF}" = 'ON' ] &&a='OFF'||a='ON'
  TABLE["$i"]="${TABLE["$i"]} $a"
done
for i in "${TABLE[@]}"
do
  echo "$i"
done