1. 程式人生 > >shell指令碼關於字串操作

shell指令碼關於字串操作

字串單引號和雙引號的差別

單引號中間不能再次出現單引號,這就意味這單引號中間出現變數是無效的,直接點說,單引號中間無論出現什麼都會原樣輸出。但是單引號字串中不能出現單獨一個的單引號(對單引號使用轉義符後也不行),但可成對出現,作為字串拼接使用。雙引號中間是可以出現變數的,而且雙引號中間是可以進行字元轉移的。直接上簡單程式碼顯示:

#!/bin/bash

where="CSDN"
val1='I am in $where'
val2='I am in '$where''
val3='I am in ${where}'

val4="I am in ${where}"
echo $val1
echo $val2
echo $val3
echo $val4

輸出結果:
I am in $where
I am in CSDN
I am in ${where}
I am in CSDN

字串擷取以及查詢

在字元的查詢中,我使用的是expr函式,因此在這裡我們格外注意的是,expr函式返回的字串起始位置不是0,不是0,不是0,重要的事說三遍。比如“CSDN”,那麼當你在查詢S字元的時候,那麼返回值是2,而不是1。但是,字串擷取卻是以0開始的。比如string=“csdn” string=${string:1:2} 。。。string將是tr。程式碼如下:

#bin/bash

string="where I am is CSDN"
space_where=1
j=0
i=0
while (($space_where!=0)) 
do
        space_where=$(expr index "$string" " ")
        strend=${#string}
        if (($space_where == 0));then
                echo "$i"th   ${string:$j:$strend}
        else
                echo "$i"th   ${string:$j:$space_where-1}
        fi
        string=${string:$space_where:$strend}
        i=$[ i+1 ]
done

輸入結果如下:
0th where
1th I
2th am
3th is
4th CSDN