Shell中的${}、##和%%幾點說明
復制代碼 代碼如下:
file=/dir1/dir2/dir3/my.file.txt
可以用${ }分別替換得到不同的值:
復制代碼 代碼如下:
${file#*/}:刪掉第一個 / 及其左邊的字符串:dir1/dir2/dir3/my.file.txt
${file##*/}:刪掉最後一個 / 及其左邊的字符串:my.file.txt
${file#*.}:刪掉第一個 . 及其左邊的字符串:file.txt
${file##*.}:刪掉最後一個 . 及其左邊的字符串:txt
${file%/*}:刪掉最後一個 / 及其右邊的字符串:/dir1/dir2/dir3
${file%%/*}:刪掉第一個 / 及其右邊的字符串:(空值)
${file%%.*}:刪掉第一個 . 及其右邊的字符串:/dir1/dir2/dir3/my
記憶的方法為:
復制代碼 代碼如下:
# 是 去掉左邊(鍵盤上#在 $ 的左邊)
%是去掉右邊(鍵盤上% 在$ 的右邊)
單一符號是最小匹配;兩個符號是最大匹配
${file:0:5}:提取最左邊的 5 個字節:/dir1
${file:5:5}:提取第 5 個字節右邊的連續5個字節:/dir2
也可以對變量值裏的字符串作替換:
復制代碼 代碼如下:
${file/dir/path}:將第一個dir 替換為path:/path1/dir2/dir3/my.file.txt
(2)
## #後面如果直接跟匹配的字符串,會刪除前面的或者左邊的所有字符串,主要通配符的位置(# ## *必須在前面比如*llo);跟完整字符串只匹配第一個,效果一樣,如果完整字符串不是第一個,原樣輸出
%% %後面如果直接跟匹配的字符串,會刪除前面的或者右邊邊的所有字符串,主要通配符的位置(% %% *必須在在後面比如he*),跟完整字符串原樣輸出
比如
a=" this is hello a maomaochong hello this!"
35 #echo ${a#hello} //this is hello a maomaochong hello this!
36 #echo ${a##hello}//this is hello a maomaochong hello this!
37 #echo ${a#*llo} //a maomaochong hello this!
38 #echo ${a##*llo} //this !
39 echo ${a%this}//this is hello a maomaochong hello this!
40 echo ${a%%this}//this is hello a maomaochong hello this!
41 #echo ${a%he*} // this is hello a maomaochong
42 #echo ${a%%he*}//this is
//
Shell中的${}、##和%%幾點說明