将字符串拆分为数组

时间:2009-10-24 11:44:01

标签: bash unix

我想拆分字符串并构造数组。我尝试了以下代码:

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

你能告诉我吗?

5 个答案:

答案 0 :(得分:15)

以下是我将如何处理此问题:使用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

答案 1 :(得分:5)

如果您肯定想在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

答案 2 :(得分:4)

请注意,正如我在这些解决方案中经常看到的那样保存和恢复IFS会产生副作用,即如果未设置IFS,它最终会变为空字符串,这会导致后续拆分出现奇怪问题。

这是我提出的解决方案,基于Anton Olsen's扩展来处理由冒号分隔的&gt; 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

答案 3 :(得分:3)

Ksh或Bash

#! /bin/sh
myString="first column:second column:third column"
IFS=: A=( $myString )

echo ${A[0]}
echo ${A[1]}

答案 4 :(得分:2)

看起来您已经找到了解决方案,但请注意,您可以完全取消使用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