Bash映射两个数组

时间:2017-07-14 09:35:36

标签: arrays linux bash shell

我在下面定义了2个数组。

ARR1

"name": "key1", "value": "value1"
"name": "key2", "value": "value2"
"name": "key3", "value": "value3"

ARR2

value1=/other/path/to/file1
value3=/other/path/to/file3

我想映射这两个数组,使得生成的数组必须如下所示。

输出数组

"name": "key1", "value": "/other/path/to/file1"
"name": "key2", "value": "value2"
"name": "key3", "value": "/other/path/to/file3"

所以基本上我需要在我的bash脚本中编写一些命令来执行这样的映射并为我提供所需的输出。

declare -p Arr1 Arr2的输出是:

声明-p arr1 arr2

declare -a arr1='([0]="name:" [1]="key1," [2]="value:" [3]="value1" [4]="name:" [5]="key2," [6]="value:" [7]="value2" [8]="name:" [9]="key3," [10]="value:" [11]="value3")'
declare -a arr2='([0]="value1=/other/path/to/file1" [1]="value3=/other/path/to/file3")'

2 个答案:

答案 0 :(得分:1)

Script.sh

array1=( '"name": "key1", "value": "value1"'
'"name": "key2", "value": "value2"'
'"name": "key3", "value": "value3"' )

array2=( 'value1=/other/path/to/file1' 'value3=/other/path/to/file3' )

for element in "${array2[@]}"
do
    key=`echo $element | cut -d '=' -f1`
    value=`echo $element | cut -d '=' -f2-`
    i=0
    for elem in "${array1[@]}"
    do
        array1[i]=`echo $elem | sed -e "s#$key#$value#"`
        (( i++ ))
    done
done

for element in "${array1[@]}"
do
   echo $element
done

结果:

./test.sh 
"name": "key1", "value": "/other/path/to/file1"
"name": "key2", "value": "value2"
"name": "key3", "value": "/other/path/to/file3"

答案 1 :(得分:0)

您可以在bash

中使用此脚本
declare -a arr1='([0]="name:" [1]="key1," [2]="value:" [3]="value1" [4]="name:" [5]="key2," [6]="value:" [7]="value2" [8]="name:" [9]="key3," [10]="value:" [11]="value3")'
declare -a arr2='([0]="value1=/other/path/to/file1" [1]="value3=/other/path/to/file3")'

arr=()

for i in "${arr1[@]}"; do
   s="$i"
   if [[ $i =~ ^value[0-9]+$ ]]; then
      for j in "${arr2[@]}"; do
         if [[ $j == $i"="* ]]; then
            s="${j#$i=}"
            break
         fi
      done
   fi
   arr+=("$s")
done

# print formatted output
#declare -p arr
for i in "${arr[@]}"; do
   printf "%s" "$i"
   ((++n % 4 == 0)) && printf "\n" || printf " "
done

<强>输出:

name: key1, value: /other/path/to/file1
name: key2, value: value2
name: key3, value: /other/path/to/file3