繁体   English   中英

将逗号分隔的字符串拆分为多个单词,以便我可以遍历每个单词

[英]Splitting a comma separated string into multiple words so that I can loop through each word

我想在Bash中拆分一个字符串供for循环使用。 例如,我有这个字符串

hello,my,name,is,mindia

我想将其拆分为单个单词,以便我可以遍历每个单词。 有人可以帮我吗?

非常简单的方法是使用分词来排列:

s="hello,my,name,is,mindia"

您将输入字段分隔符设置为,:

IFS=,

然后将字符串拆分为数组:

a=( $s )

结果:

for word in "${a[@]}"; do echo "- [$word]"; done

使用纯且不split (或者可能是cut ):

string="hello,my,name,is,mindia"
IFS=, read -r -a array <<< "$string"
# at this point your fields are in the array array
# you can loop through the fields like so:
for field in "${array[@]}"; do
    # do stuff with field field
done
# you can print the fields one per line like so
printf "%s\n" "${array[@]}"

警告 如果您尝试解析csv文件,则该文件迟早会中断,例如,

field 1,"field 2 is a string, with a coma in it",field 3

好点 但是,与其他答案相比,有一个好处:如果您的字段中有空格,则此方法仍然有效:

$ string="hello,this field has spaces in it,cool,it,works"
$ IFS=, read -r -a array <<< "$string"
$ printf "%s\n" "${array[@]}"
hello
this field has spaces in it
cool
it
works

另一个好处是, IFS不是全局设置的。 它仅针对read命令设置:以后忘记了全局设置IFS时,不会有任何意外!

您可以使用模式替换:

s="hello,my,name,is,mindia"
for i in ${s//,/ }
do
    echo $i
done

这是可以处理空格的版本:

while IFS= read -r -d ',' i; do
    printf "%s\n" "$i"
done <<<"${s:+$s,}"
root$ s="hello,my,name,is,mindia"
root$ for i in $(echo "$s" | tr "," "\n"); do echo $i;done

hello
my
name
is
mindia

修复了空格问题:

s="a,b,c   ,d,f";
a="";
while [[ $s != $a ]] ; do 
    a="$(echo $s | cut -f1  -d",")";
    echo $a;
    s="$(echo $s | cut -f2- -d",")"; 
done

和输出:

a
b
c
d
f

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM