在 bash 中使用参数扩展从这个字符串中提取joebloggs,而不需要任何额外的过程...
MYVAR="/var/cpanel/users/joebloggs:DNS9=domain.com"
NAME=${MYVAR%:*} # retain the part before the colon
NAME=${NAME##*/} # retain the part after the last slash
echo $NAME
不依赖于joebloggs 在路径中的特定深度。
总结
几种参数扩展方式的概述,供参考……
${MYVAR#pattern} # delete shortest match of pattern from the beginning
${MYVAR##pattern} # delete longest match of pattern from the beginning
${MYVAR%pattern} # delete shortest match of pattern from the end
${MYVAR%%pattern} # delete longest match of pattern from the end
所以# 表示从头开始匹配(想想注释行),% 表示从结尾匹配。一个实例表示最短,两个实例表示最长。
您可以使用数字根据位置获取子字符串:
${MYVAR:3} # Remove the first three chars (leaving 4..end)
${MYVAR::3} # Return the first three characters
${MYVAR:3:5} # The next five characters after removing the first 3 (chars 4-9)
您还可以使用以下方法替换特定的字符串或模式:
${MYVAR/search/replace}
pattern 与文件名匹配的格式相同,因此*(任何字符)很常见,通常后跟特定符号,如/ 或.
示例:
给定一个像
这样的变量
MYVAR="users/joebloggs/domain.com"
删除留下文件名的路径(所有字符直到斜线):
echo ${MYVAR##*/}
domain.com
去掉文件名,留下路径(删除最后一个/之后的最短匹配):
echo ${MYVAR%/*}
users/joebloggs
仅获取文件扩展名(删除最后一个句点之前的所有内容):
echo ${MYVAR##*.}
com
注意: 要执行两个操作,您不能将它们组合起来,而必须分配给一个中间变量。所以要获取没有路径或扩展名的文件名:
NAME=${MYVAR##*/} # remove part before last slash
echo ${NAME%.*} # from the new var remove the part after the last period
domain