使用bash/cut/split提取字符串的一部分
我有一个这样的字符串:
/var/cpanel/users/joebloggs:DNS9=domain.com 我需要从这个字符串中提取用户名:joebloggs,并将其存储在一个变量中 字符串的格式将始终是相同的,除了joebloggs和domain.com所以我认为字符串可以拆分两次使用“剪切”? 第一次拆分将使用:将我们分开的字符串,我们将存储第一部分在一个varibale传递给第二个拆分功能。 第二次拆分将使用/拆分字符串,并将最后一个字(joebloggs)存储到一个变量中 我知道如何做这个在php使用数组和拆分,但在bash我有点失去了。
使用参数扩展在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在路径中的特定深度。 如果你想使用grep: echo MYVAR | grep -oE '/[^/]+:' | cut -c2- | rev | cut -c2- | rev 概要 几个参数扩展模式的概述,供参考… ${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/search/replace} 该模式与文件名匹配格式相同,因此*(任何字符)是常见的,后面紧跟着/或的特殊符号。 例子: 给定一个变量like 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |