Linux 字符竄截取的方法彙總
1.命令彙總
${target-string#*sub-string}
${target-string##*sub-string}
${target-string%sub-string*}
${target-string%%*sub-string*}
----------------------------------------------------------------------------
${target-string:start-index:string-numbers}
${target-string:start-index}
${target-string:0-start_index:string-numbers}
${target-string:0-start_index}
2.例子彙總
st1=‘http://www.baidu.com/image/image.png’
從st1的 左邊開始截掉‘/’這個字符第一次出現的位置左邊的部分,保留右邊部分且不包含‘/’。
# echo ${st1#*/} /www.baidu.com/image/image.png
從st1的 左邊開始截掉‘/’這個字符最後一次出現的位置左邊的部分,保留右邊部分且不包含‘/’。
# echo ${st1##*/} image.png
----------------------------------------------------------------------------
st1=‘http://www.baidu.com/image/image.png’
從st1的 右邊開始截掉‘/’這個字符第一次出現的位置右邊的部分,保留左邊部分且不包含‘/’。
# echo ${st1%/*} http://www.baidu.com/image
從st1的 右邊開始截掉‘/’這個字符最後一次出現的位置右邊的部分,保留左邊部分且不包含‘/’。
# echo ${st1%%/*} http:
-----------------------------------------------------------------------------
st1=‘http://www.baidu.com/image/image.png’
從st1的 左邊開始,從第一個字符{0}開始,截取{4}4個字符。
# echo ${st1:0:4} http
從st1的 左邊開始,截掉7個字符,保留右邊的部分
# echo ${st1:7} www.baidu.com/image/image.png
---------------------------------------------------------------------------------------
st1=‘http://www.baidu.com/image/image.png’
從st1的 右邊第10個字符{0-10}開始,截取6個字符。
# echo ${st1:0-10:6} /image #不是ge.png ,因爲是從第右邊開始第10個字符,即從‘/’數6個字符。
從st1的 右邊第10個字符{0-10}開始,截取右邊所有字符。
# echo ${st1:0-10} /image.png
3.記憶方法
一定要分清楚是截取 ,還是截掉。
符號總共有5個, '#' '##' '%' ‘%%’ '*'
#