我需要一个下面的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
此处op1
到op14
是变量,我必须存储这些值。
答案 0 :(得分:2)
首先使用单个唯一字符分隔符替换#@#
,例如#
,然后使用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