How to use the specified separator to split a string so that the result is an array of strings, similar to split in java, and the split keyword has been left for file segmentation, so the string segmentation process cannot be used. So how to handle string segmentation? There are two methods
1. For strings that do not contain spaces, use the following method
Method 1
#!/bin/bash string="hello,shell,haha" array=(${string//,/ }) for var in ${array[@]} do echo $var done
Method 2
#!/bin/bash string="hello,shell,haha" OLD_IFS="$IFS" IFS="," array=($string) IFS="$OLD_IFS" for var in ${array[@]} do echo $var done
Method 3: Use the tr instruction to implement character replacement
#!/bin/bash string="one,two,three,four,five" array=(`echo $string | tr ',' ' '` ) for var in ${array[@]} do echo $var done
2. For strings containing spaces, use the following method
#!/bin/bash str='this is a good question, hello shell, look at me, show your enthusiasm' i=1 while((1==1)) do splitchar=`echo $str|cut -d "," -f$i` if [ "$splitchar" != "" ] then ((i++)) echo $splitchar else break fi done
This is the end of this article about how shells use specified splitting characters to split strings. For more related shells, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!