写程式经常需要做字串处理,其中一项常做的是字串分割。在 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.