Shell string truncation rules: • $ {# parameter} gets the string length. • $ {parameter % word} captures word at the end of the string at a minimum. • $ {parameter % word} captures word at the end of the string to the maximum extent. • $ {parameter # word} captures word at least from the front • $ {parameter # word} to the maximum extent from the front
I wrote a small program. For shell string truncation, save it to prevent forgetting:
!/bin/bash #|--------------------------------------| #|Author: Liwenta | #|Email: email.tata@qq.com | #|Date: 2013-01-05 | #|--------------------------------------| str="/project/mkdemo/src" echo '${str}='${str} echo '${#str}='${#str} tmp=`dirname ${str}` echo 'dirname ${str}='${tmp} tmp=`basename ${str}` echo 'basename ${str}='${tmp} tmp=${str#*/} echo '${str#*/}='${tmp} tmp=${str##*/} echo '${str##*/}='${tmp} tmp=${str%/*} echo '${str%/*}='${tmp}
Running result:
[root@tata.domain /andes/shell/string]#./ph.sh ${str}=/project/mkdemo/src ${#str}=19 dirname ${str}=/project/mkdemo basename ${str}=src ${str#*/}=project/mkdemo/src ${str##*/}=src ${str%/*}=/project/mkdemo ${str%%/*}=