shell如何将字符串按逗号分割并放入数组

2024-11-16 08:59:50
推荐回答(1个)
回答(1):

root@localhost:~/xly# sh 1 hello
abc
shell
haha
1 hello abc
2 shell
3 haha
root@localhost:~/xly# vim 1
#!/bin/bash
string="hello abc,shell,haha"
OLD_IFS="$IFS"
IFS=","
array=($string)
IFS="$OLD_IFS"
for var in ${array[@]}
do
echo $var
done

echo $string | awk '{split($0,arr,",");for(i in arr) print i,arr[i]}'

用awk更加精准