Shell教程 之字符串
阿新 • • 發佈:2018-08-29
blog 優點 .com 註意 開始 clas 成對出現 提取子字符串 index
1.Shell字符串
字符串是shell編程中最常用最有用的數據類型(除了數字和字符串,也沒啥其它類型好用了),字符串可以用單引號,也可以用雙引號,也可以不用引號。
1.1 單引號
str=‘I am uniquefu‘
單引號字符串的限制:
- 單引號裏的任何字符都會原樣輸出,單引號字符串中的變量是無效的;
- 單引號字串中不能出現單獨一個的單引號(對單引號使用轉義符後也不行),但可成對出現,作為字符串拼接使用
1.2 雙引號
name="http://www.cnblogs.com/uniquefu" str="Hello, I know you are \"$name\"! \n" echo ${str}
輸出結果:
[root@test3101-3 bin]# ./test.sh Hello, I know you are "http://www.cnblogs.com/uniquefu"! \n
雙引號的優點:
- 雙引號裏可以有變量
- 雙引號裏可以出現轉義字符
1.3 拼接字符串
your_name="uniquefu" # 使用雙引號拼接 greeting="hello, "$your_name" !" greeting_1="hello, ${your_name} !" echo $greeting $greeting_1 # 使用單引號拼接 greeting_2=‘hello, ‘$your_name‘ !‘ greeting_3=‘hello, ${your_name} !‘ echo $greeting_2 $greeting_3
運行結果
[root@test3101-3 bin]# ./test.sh hello, uniquefu ! hello, uniquefu ! hello, uniquefu ! hello, ${your_name} !
1.4 獲取字符串長度
your_name="uniquefu" echo ${#your_name}
輸出結果:
[root@test3101-3 bin]# ./test.sh 8
1.5 提取子字符串
以下實例從字符串第 3 個字符開始截取 5 個字符
your_name="uniquefu" echo ${your_name:2:5}
輸出結果:
[root@test3101-3 bin]# ./test.sh iquef
1.6 查找字符串
查找字符 i 或 f 的位置(哪個字母先出現就計算哪個):
your_name="uniquefu" echo `expr index "$your_name" if` # 輸出 3
註意: 以上腳本中 ` 是反引號,而不是單引號 ‘,不要看錯了哦
Shell教程 之字符串