Shell中的${}、##和%%使用範例

轉自:https://www.cnblogs.com/Template/p/9079470.html

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
${file%%.*}:  刪掉第一個 . 及其右邊的字符串:/dir1/dir2/dir3/my
${file: -1}: 打印最後一個字符

複製代碼

記憶的方法爲:
#是 去掉左邊(鍵盤上#在 $ 的左邊)
%  是去掉右邊(鍵盤上% 在$ 的右邊)
單一符號是非貪婪匹配;兩個符號是貪婪匹配

${file:0:5}:提取最左邊的 5 個字節:/dir1
${file:5:5}:提取第 5 個字節右邊的連續5個字節:/dir2

也可以對變量值裏的字符串作替換:
${file/dir/path}:將第一個dir 替換爲path:/path1/dir2/dir3/my.file.txt
${file//dir/path}:將全部dir 替換爲 path:/path1/path2/path3/my.file.txt

[root@localhost ~]# p=123abc
[root@localhost ~]# echo ${p//[0-9]/}      #將變量中的數字替換爲空
abc

±---------------------------------------------------------------------+
|Form Meaning
±---------------------------------------------------------------------+
|${variable:?word} Complain if undefined or null
|${variable:-word} Use new value if undefined or null
|${variable:+word} Opposite of the above
|${variable:=word} Use new value if undefined or null, and redefine.
±---------------------------------------------------------------------+
複製代碼

foo=${bar:-something}

echo $foo # something
echo $bar # no assignement to bar, bar is still empty

foo=${bar:=something}

echo $foo # something
echo $bar # something too, as there’s an assignement to bar

複製代碼

man bash :

${parameter:-word}
Use Default Values. If parameter is unset or null, the expansion of word is substituted. Otherwise,
the value of parameter is substituted.
${parameter:=word}
Assign Default Values. If parameter is unset or null, the expansion of word is assigned to parameter.
The value of parameter is then substituted. Positional parameters and special parameters may not be
assigned to in this way.
${parameter:?word}
Display Error if Null or Unset. If parameter is null or unset, the expansion of word (or a message to
that effect if word is not present) is written to the standard error and the shell, if it is not inter-
active, exits. Otherwise, the value of parameter is substituted.
${parameter:+word}
Use Alternate Value. If parameter is null or unset, nothing is substituted, otherwise the expansion of
word is substituted.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章