1

我需要下面的shell脚本。

我有 14 个变量:

场景 1 输入:

a#@#b#@#c#@#d#@#e#@#f#@#g#@#e#@#f#@#g#@#h#@#i#@#j#@#k#@#l#@#m#@#n

场景 2 输入:

a#@#b#@#c#@#d#@#e#@#f#@#g#@#e#@#f#@#g#@#h#@#i#@#j#@#k#@#l#@#m#@#n#@#

我想要输出为

op1 = a

op2 = b

op3 = c

op4 = d

op5 = e

op6 = g

op7 = f

op8 = h

op9 = i

op10 = j

op11 = k

op12 = l

op13 = m

op14 = n

这里op1op14变量,我必须在其中存储值。

4

1 回答 1

3

首先#@#用一个唯一的字符分隔符替换,例如#,然后使用read将其读入数组。数组的元素包含字符。这如下所示。

$ input="a#@#b#@#c#@#d#@#e#@#f#@#g#@#e#@#f#@#g#@#h#@#i#@#j#@#k"
$ IFS='#' read -a arr  <<< "${input//#@#/#}"
$ echo ${arr[0]}
a
$ echo ${arr[1]}
b
$ echo ${arr[13]}
k

# print out the whole array
$ for (( i=0; i<${#arr[@]}; i++ ))
> do
>     echo "Element at index $i is ${arr[i]}"
> done
Element at index 0 is a
Element at index 1 is b
Element at index 2 is c
Element at index 3 is d
Element at index 4 is e
Element at index 5 is f
Element at index 6 is g
Element at index 7 is e
Element at index 8 is f
Element at index 9 is g
Element at index 10 is h
Element at index 11 is i
Element at index 12 is j
Element at index 13 is k
于 2012-12-14T09:25:26.387 回答