我想拆分一个字符串,以便在Bash中使用for -循环。例如,我有一个字符串
hello,my,name,is,mindia我想把它分割成单独的单词,这样我就可以循环遍历每个单词。有人能帮我吗?
发布于 2013-06-22 10:36:29
非常简单的方法是使用分词来排列:
s="hello,my,name,is,mindia"将输入字段分隔符设置为:
IFS=,然后将字符串拆分为数组:
a=( $s )结果:
for word in "${a[@]}"; do echo "- [$word]"; done发布于 2013-06-22 10:34:44
使用纯bash而不使用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时,没有什么不好的惊喜!
发布于 2013-06-22 10:30:34
您可以使用模式替换:
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,}"https://stackoverflow.com/questions/17249665
复制相似问题