Get length
${#str}
Get sub-string
${str:0:3} #start-pos, length
${str:1} #start-pos
For example
#!/bin/ksh
STR="12345678"
echo ${STR:0:2} # get first 2: 12
echo ${STR#${STR%??}} # get last 2 : 78
echo ${STR:2} # cut first 2: 345678
echo ${STR%??} # cut last 2 : 123456Variable Expansion Formats
${variable:-word}
value of variable if set and not null, else print word
${variable:=word}
value of variable if set and not null, else variable is set to word , then expanded
${variable:+word}
value of word if variable is set and not null, else nothing is substituted
${variable:?word}
value of variable if set and not null, else print value of word and exit
${variable#pattern}
value of variable without the smallest beginning portion that matches pattern
${variable##pattern}
value of variable without the largest beginning portion that matches pattern
For example
- PROGRAM=${0##*/} # get the program name, strip the path
- FILE=${1##*/} # get the file name of first parm, strip the path
${variable%pattern}
value of variable without the smallest ending portion that matches pattern
${variable%%pattern}
value of variable without the largest ending portion that matches pattern
${variable//pattern1/pattern2}
replace all occurrences of pattern1 with pattern2 in variable
Delete sub-string
${var%%A*} # delete all chars at the right of first char ‘A’; “12A34A56” => “12”
${var%A*} # delete all chars at the right of last char ‘A’; “12A34A56” => “12A34”
${var##A*} # delete all chars at the left of last char ‘A’; “12A34A56” => “56”
${var#A*} # delete all chars at the left of first char ‘A’; “12A34A56” => “34A67”Replace sub-string
${var/A/B} # replace first ‘A’ with ‘B’; “12A34A56” => “12B34A56”
${var//A/B} # replace all ‘A’ with ‘B’; “12A34A56” => “12B34B56”
String starts/ends with a sub-string
AA="ABCD"
BB="EFGH"
CC="AB"
DD="GH"
[[ "${AA}" =~ "^AB" ]] && echo "YES" || echo "NO" # ${AA} starts with "AB": Y
[[ "${BB}" =~ "^AB" ]] && echo "YES" || echo "NO" # ${BB} starts with "AB": N
[[ "${AA}" =~ "CD$" ]] && echo "YES" || echo "NO" # ${AA} ends with "CD": Y
[[ "${BB}" =~ "CD$" ]] && echo "YES" || echo "NO" # ${AA} ends with "CD": N
[[ "${AA}" =~ "^${CC}" ]] && echo "YES" || echo "NO" # ${AA} starts with ${CC}: Y
[[ "${AA}" =~ "^${DD}" ]] && echo "YES" || echo "NO" # ${AA} starts with ${DD}: N
[[ "${BB}" =~ "${CC}$" ]] && echo "YES" || echo "NO" # ${AA} ends with ${CC}: N
[[ "${BB}" =~ "${DD}$" ]] && echo "YES" || echo "NO" # ${AA} ends with ${DD}: Y

本文介绍Shell脚本中字符串的各种操作方法,包括获取长度、子串提取、替换等实用技巧,并展示了如何通过变量扩展格式实现这些功能。

被折叠的 条评论
为什么被折叠?



