寫程式經常需要做字串處理,其中一項常做的是字串分割。在 PHP 有一個很好用的函式是 explode(), 可以根據指定的分割字符,將字串分割,並把每一組分割後的字串放到 array 內.
在 Shell Script 要這樣分割字串,可以用 $IFS 變數實現,以下是 Shell Script 的寫法:
1 2 3 4 5 6 7 8 9 10 |
#!/bin/sh str="This is a testing." OIFS="$IFS" IFS=' ' read -a new_string <<< "${str}" IFS="$OIFS" echo ${new_string[0]} |
上面會將字串 “This is a testing.” 以空格分割,並會將分割後的字串放到 new_string 陣列,最後印出該陣列第一個元值,即 “This”.
如果想將分割後的字串逐一印出,可以改成這樣:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#!/bin/sh str="This is a testing." OIFS="$IFS" IFS=' ' read -a new_string <<< "${str}" IFS="$OIFS" for i in "${new_string[@]}" do echo "$i" done |
上面程式的執行結果是:
This
is
a
testing.