将字符串拆分为数组

2023-12-24

我想分割字符串并构造数组。我尝试了下面的代码:

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

你能给些建议么?


以下是我解决此问题的方法:使用 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

Run it:

$ ./split.sh
Element 0: first column
Element 1: second column
Element 2: third column
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将字符串拆分为数组 的相关文章

随机推荐