Posted on 2009-08-28 13:29
Prayer 閱讀(682)
評(píng)論(0) 編輯 收藏 引用 所屬分類:
Shell
1: shell 中比較好用的獲得字符串的兩個(gè)函數(shù)是basename 和dirname .其中basename得到具體文件名(或目錄中的最后那部分),另外的部分可以由dirname得到:
> basename /r/sanyo.unx.sas.com/vol/vol5/u51/scnyam/meiplaypen/mei_shell
mei_shell
> dirname /r/sanyo.unx.sas.com/vol/vol5/u51/scnyam/meiplaypen/mei_shell
/r/sanyo.unx.sas.com/vol/vol5/u51/scnyam/meiplaypen
2: 但是這種處理顯然無法滿足所有類型字符串的截取要求。 不過不用擔(dān)心,bash本身有它截取字符串的簡單方法:
我們來看下面的例子:
var=PeterPiPerPickedofPick # PeterPiperPickedaPeckofPickledPepper (the famsous and classic tongue twister, coudl you speak it correctly and fluently??)
> echo ${var#*Pe}
terPiPerPickedofPick
> echo ${var##*Pe}
rPickedofPick
> echo ${var%Pi*}
PeterPiPerPickedof
> echo ${var%%Pi*}
Peter
看到了嗎? #是從左側(cè)替換 進(jìn)行替換,%是從右側(cè)。為什么呢? 因?yàn)殒I盤上的位置是:#$% 即#在$的左邊, %在$的右邊。
神秘吧?
小例子:
#!/bin/bash
if [ "${1##*.}" = "tar" ]
then
echo This appears to be a tarball.
else
echo At first glance, this does not appear to be a tarball.
fi
參考文章: 截?cái)嘧址攀觯?位置找不到了。