使用参数扩展在bash中从此字符串中提取joebloggs
,而不需要任何额外的进程...
MYVAR="/var/cpanel/users/joebloggs:DNS9=domain.example"
NAME=${MYVAR%:*}
NAME=${NAME##*/}
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.example"
去除路径,只保留文件名(删除斜杠前的所有字符):
echo ${MYVAR##*/}
domain.example
删除文件名,只保留路径(删除最后一个 /
后面的字符):
echo ${MYVAR%/*}
users/joebloggs
获取文件扩展名(删除最后一个句点之前的所有内容):
echo ${MYVAR##*.}
example
注意:要执行两个操作,不能将它们组合在一起,而是必须分配给一个中间变量。因此,要获取不带路径或扩展名的文件名:
NAME=${MYVAR##*/}
echo ${NAME%.*}
domain
#
代替%
。如果你只想获取最后一个冒号后面的部分,可以使用${MYVAR##*:}
;如果想要获取第一个冒号后面的部分,可以使用${MYVAR#*:}
。请注意不要改变原意。 - beroe${RET##*$CHOP}
还是像这样${RET##*CHOP}
(或者其他方式)? 编辑:看起来应该是前者${RET##*$CHOP}
。 - Ctrl S${MYVAR::3}
表达式无法工作。会返回“zsh:需要闭合括号”的错误信息。相反,:3:5
或仅使用:3
可以正常工作。 - dimisjim