开发者

bash : adding a name value to a structure using bash

I want to do the following in bash for example say i have the following names rather than creating three seperate arrays to hold the contents of LC1 , LC2 and LC3 i thought it might be best to create a tree structure in bash or maybe someone might have a neater solution - I need to do this in bash .

 LC1
    Test1
 开发者_如何转开发   Test2
 LC2
    Test3
    Test4
 LC3
    Test5
    Test6


You can simulate a multidimensional structure. With bash4, for instance, you could use an associative array:

declare -A a=(
  [LC1]="Test1 Test2"
  [LC2]="Test3 Test4"
  [LC3]="Test5 Test6"
    ) 

for k in "${!a[@]}"; do
  printf '%s\n' "$k"
  set -- ${a["$k"]} # by default split on white space, tab and newline
                    # you can use another delimiter, if you wish
  for e; do
    printf '\t => %s\n' "$e"
  done
done 

The code produces:

4.1.10(4)-release$ for k in "${!a[@]}"; do
>   printf '%s\n' "$k"
>   set -- ${a["$k"]} # by default split on white space, tab and newline
>                     # you can use another delimiter, if you wish
>   for e; do
>     printf '\t => %s\n' "$e"
>   done
> done 
LC1
         => Test1
         => Test2
LC3
         => Test5
         => Test6
LC2
         => Test3
         => Test4

Bare in mind that the set command will reset your positional parameters.


@killio, I'm posting a new answer, because the comments provide limited formatting.

You could modify the array like this: just to give an example, if you want to double the last character of the elements:

#!/bin/bash


a=( 
  'LC1 Test1 Test2' 
  'LC2 Test3 Test4' 
  'LC3 Test5 Test6' 
  ) 

printf '\nthe array before:\n\n' 
printf '%s\n' "${a[@]}"


for ((i=0; i < ${#a[@]}; i++)); do 
  k=${a[i]%% *} es=${a[i]#* }
  set -- $es
  for e; do
   (( !c++ )) && es=$e${e#${e%?}} || es="$es $e${e#${e%?}}"
  done
  a[$i]="$k $es"; c=0
done


printf '\n\nthe array after:\n\n' 
printf '%s\n' "${a[@]}"



 $ ./s

the array before:

LC1 Test1 Test2
LC2 Test3 Test4
LC3 Test5 Test6


the array after:

LC1 Test11 Test22
LC2 Test33 Test44
LC3 Test55 Test66
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜