将string分割成数组

我想拆分string并构造数组。 我试了下面的代码:

myString="first column:second column:third column" set -A myArray `echo $myString | awk 'BEGIN{FS=":"}{for (i=1; i<=NF; i++) print $i}'` # Following is just to make sure that array is constructed properly i=0 while [ $i -lt ${#myArray[@]} ] do echo "Element $i:${myArray[$i]}" (( i=i+1 )) done exit 0 It produces the following result: Element 0:first Element 1:column Element 2:second Element 3:column Element 4:third Element 5:column This is not what I want it to be. When I construct the array, I want that array to contain only three elements. Element 0:first column Element 1:second column Element 2:third column 

你能给些build议么?

下面是我将如何处理这个问题:使用IFS变量告诉shell(bash)你想把字符串拆分成冒号分隔的标记。

 $ cat split.sh #!/bin/sh # Script to split fields into tokens # Here is the string where tokens separated by colons s="first column:second column:third column" IFS=":" # Set the field separator set $s # Breaks the string into $1, $2, ... i=0 for item # A for loop by default loop through $1, $2, ... do echo "Element $i: $item" ((i++)) done 

运行:

 $ ./split.sh Element 0: first column Element 1: second column Element 2: third column 

如果你肯定想在Bash中使用数组,你可以尝试这种方式

 $ myString="first column:second column:third column" $ myString="${myString//:/ }" #remove all the colons $ echo "${myString}" first column second column third column $ read -a myArr <<<$myString $ echo ${myArr[@]} first column second column third column $ echo ${myArr[1]} column $ echo ${myArr[2]} second 

否则,“更好”的方法是完全使用awk

请注意,正如我在这些解决方案中经常看到的那样,保存和恢复IFS具有副作用,即如果IFS未设置,则最终会变成空字符串,从而导致随后分裂的奇怪问题。

这是我根据Anton Olsen的扩展来处理由冒号分隔的> 2个值的解决方案。 它处理列表中具有正确空格的值,而不是分割空间。

 colon_list=${1} # colon-separate list to split while true ; do part=${colon_list%%:*} # Delete longest substring match from back colon_list=${colon_list#*:} # Delete shortest substring match from front parts[i++]=$part # We are done when there is no more colon if test "$colon_list" = "$part" ; then break fi done # Show we've split the list for part in "${parts[@]}"; do echo $part done 

Ksh或Bash

 #! /bin/sh myString="first column:second column:third column" IFS=: A=( $myString ) echo ${A[0]} echo ${A[1]} 

看起来你已经找到了解决方案,但是请注意,你可以完全废除awk:

 myString="first column:second column:third column" OIFS="$IFS" IFS=':' myArray=($myString) IFS=$OIFS i=0 while [ $i -lt ${#myArray[@]} ] do echo "Element $i:${myArray[$i]}" (( i=i+1 )) done