简体   繁体   English

重击追加到数组元素的末尾

[英]Bash append to end of array element

I have a command, when I run it, it output a table that looks like; 我有一个命令,当我运行它时,它输出一个看起来像的表;

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

I then store the table in an array call TABLE and list the TABLE array, the code looks like this; 然后,将表存储在调用TABLE的数组中并列出TABLE数组,代码如下所示;

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

How do I append to the end of each array element? 如何附加到每个数组元素的末尾? I want the table to be presented as following; 我希望表格显示如下:

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

What does the command "$(command)" do? 命令"$(command)"做什么? Should we assume, that one line of the output = one string = one element of the array? 我们是否应该假设输出的一行=一个字符串=数组的一个元素? If so, then this should work for you: 如果是这样,那么这应该为您工作:

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

But this is a general answer. 但这是一个普遍的答案。 You could improve your question by showing us what your input is and how is it processed before it is printed. 您可以通过向我们显示输入内容以及在打印之前如何对其进行处理来改善您的问题。

If you want to append ON or OFF in your array 如果要在数组中附加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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM