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/p_w_picpath/p_w_picpath.png’


  • 从st1的 左边开始截掉‘/’这个字符第一次出现的位置左边的部分,保留右边部分且不包含‘/’。

# echo ${st1#*/}

/www.baidu.com/p_w_picpath/p_w_picpath.png


  • 从st1的 左边开始截掉‘/’这个字符最后一次出现的位置左边的部分,保留右边部分且不包含‘/’。

# echo ${st1##*/}

p_w_picpath.png

 

----------------------------------------------------------------------------


st1=‘http://www.baidu.com/p_w_picpath/p_w_picpath.png’


  • 从st1的 右边开始截掉‘/’这个字符第一次出现的位置右边的部分,保留左边部分且不包含‘/’。

# echo ${st1%/*}

http://www.baidu.com/p_w_picpath


  • 从st1的 右边开始截掉‘/’这个字符最后一次出现的位置右边的部分,保留左边部分且不包含‘/’。

# echo ${st1%%/*}

http:


-----------------------------------------------------------------------------


st1=‘http://www.baidu.com/p_w_picpath/p_w_picpath.png’


  • 从st1的 左边开始,从第一个字符{0}开始,截取{4}4个字符。

# echo ${st1:0:4}

http


  • 从st1的 左边开始,截掉7个字符,保留右边的部分

# echo ${st1:7}

www.baidu.com/p_w_picpath/p_w_picpath.png


---------------------------------------------------------------------------------------


st1=‘http://www.baidu.com/p_w_picpath/p_w_picpath.png’


  • 从st1的 右边第10个字符{0-10}开始,截取6个字符。

# echo ${st1:0-10:6}

/p_w_picpath    #不是ge.png ,因为是从第右边开始第10个字符,即从‘/’数6个字符。


  • 从st1的 右边第10个字符{0-10}开始,截取右边所有字符。

# echo ${st1:0-10}

/p_w_picpath.png


3.记忆方法


  • 一定要分清楚是截取 ,还是截掉。

  • 符号总共有5个, '#'    '##'    '%'    ‘%%’    '*'     


#