2012-12-14 44 views
1

我需要下面的shell腳本。用於從分隔值獲取有限值的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是變量,其中我必須存儲的值。

回答

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 
+0

什麼是IFS ?? .. –

+0

IFS是內部字段分隔符,用於與'read'內置命令分割線成單詞。 – dogbane

+0

可以請你解釋一下這個部分''讀-a arr <<<「$ {input //#@#/#}」' –