shell 字符串轉數組


 

#!/bin/bash
string="hello,shell,split,test" 
#將,替換為空格 
array=(${string//,/ })  
 
for var in ${array[@]}
do
   echo $var
done 

輸出

bogon:conf macname$ ./test.sh 
hello
shell
split
test

 

還可以寫成

#!/bin/bash
string="hello,shell,split,test"  
array=(`echo $string | tr ',' ' '` )  
 
for var in ${array[@]}
do
   echo $var
done 
 

或者

#!/bin/bash
string="hello,shell,split,test"  
 
#對IFS變量 進行替換處理
OLD_IFS="$IFS"
IFS=","
array=($string)
IFS="$OLD_IFS"
 
for var in ${array[@]}
do
   echo $var
done

 

 

 

參考:

https://blog.csdn.net/u010003835/article/details/80750003

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM