2011-08-16 191 views
2

如何在shell腳本中標記字符串?
例如:給定字符串「a:b:c」和分隔符「:」,我想返回一個數組{a,b,c}
它等同於java的StringTokenizer。在shell腳本中標記字符串

+0

什麼殼?慶典? –

+2

http://stackoverflow.com/questions/918886/split-string-based-on-delimiter-in-bash –

+0

@Anders Lindahl:是bash是好的 – user881480

回答

3
var="a:b:c" 
OLDIFS=$IFS 
IFS=":" 
read -a array <<< "$(printf "%s" "$var")" 
IFS=$OLDIFS 
echo ${#array[@]} 
echo ${array[0]} 
echo ${array[1]} 
echo ${array[2]} 
+0

而不是'讀-a .. .',也可以說'array =($ var)' –

0
echo "a:b:c" | awk -F":" '{print "{"$1",",$2",",$3"}"}'