Answers:
要joebloggs使用参数扩展从bash中的此字符串中提取内容而无需任何额外的处理...
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
删除文件名,保留路径(在last之后删除最短匹配项/):
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
#代替%。如果只想要最后一个冒号${MYVAR##*:}之后的部分,请使用${MYVAR#*:}
${RET##*$CHOP}或这样${RET##*CHOP}(或其他方式)键入吗?编辑:似乎是前者${RET##*$CHOP}
定义一个这样的函数:
getUserName() {
echo $1 | cut -d : -f 1 | xargs basename
}
并将字符串作为参数传递:
userName=$(getUserName "/var/cpanel/users/joebloggs:DNS9=domain.com")
echo $userName
echo $1 | cut -d -f 1 | xargs。+1代表简洁明了的ans。
sed呢?这将在一个命令中起作用:
sed 's#.*/\([^:]*\).*#\1#' <<<$string
#被用于正则表达式的分隔,而不是/因为字符串有/它。.*/ 抓取字符串直到最后一个反斜杠。\( .. \)标记捕获组。这是\([^:]*\)。
[^:]表示除冒号外的任何字符_ ,*表示零或多个。.* 表示该行的其余部分。\1表示替换第一个(也是唯一一个)捕获组中找到的内容。这是名字。这是将字符串与正则表达式匹配的细分:
/var/cpanel/users/ joebloggs :DNS9=domain.com joebloggs
sed 's#.*/ \([^:]*\) .* #\1 #'
使用单个sed
echo "/var/cpanel/users/joebloggs:DNS9=domain.com" | sed 's/.*\/\(.*\):.*/\1/'