使用bash /剪切/分割提取字符串的一部分 [英] extract part of a string using bash/cut/split
问题描述
我有一个这样的字符串:
I have a string like this:
/var/cpanel/users/joebloggs:DNS9=domain.com
我需要提取用户名:此字符串从joebloggs并将其存储在一个变量
I need to extract the username: joebloggs from this string and store it in a variable
该字符串的格式将永远与joebloggs的例外,domain.com所以我想字符串可以用一刀切分裂两次?
The format of the string will always be the same with exception of joebloggs and domain.com so I am thinking the string can be split twice using "cut"?
首先将拆分使用分割字符串了。我们将在第一部分存储在varibale传递给第二分割功能
First split would split the string up using : and we would store the first part in a varibale to pass to the second split function.
二分裂将使用分割字符串/和最后一个字(joebloggs)存储到一个变量
Second split would split the string using / and store the last word (joebloggs) into a variable
我知道如何使用数组和分裂做到这一点在PHP,但在bash我有点失去了。
I know how to do this in php using arrays and splits but in bash I am a bit lost.
推荐答案
要使用参数扩展而无需任何额外的进程... <从这个字符串在bash提取物 joebloggs
/ p>
To extract joebloggs
from this string in bash using parameter expansion without any extra processes...
MYVAR="/var/cpanel/users/joebloggs:DNS9=domain.com"
NAME=${MYVAR%:*} # get the part before the colon
NAME=${NAME##*/} # get the part after the last slash
echo $NAME
不依赖于 joebloggs
是在路径特定深度。
如果你想要去一个有点过分使用的grep
:
If you want to go a bit overboard using grep
:
echo MYVAR | grep -oE '/[^/]+:' | cut -c2- | rev | cut -c2- | rev
摘要
几个参数扩展模式的概述,以供参考...
An overview of a few parameter expansion modes, for reference...
${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
所以#
表示从一开始比赛(想到一个注释行)和%
从最终手段。一个实例是指最短的两个实例是指最长的。
So #
means match from the beginning (think of a comment line) and %
means from the end. One instance means shortest and two instances means longest.
您也可以替换使用特定的字符串或模式:
You can also replace particular strings or patterns using:
${MYVAR/search/replace}
的模式
是相同的格式,文件名匹配,因此 *
(任何字符)是很常见,常接一个特定符号如 /
或。
The pattern
is in the same format as file-name matching, so *
(any characters) is common, often followed by a particular symbol like /
or .
例子:
给定一个变量像
MYVAR="users/joebloggs/domain.com"
删除离开路径文件名(所有字符以斜线):
Remove the path leaving file name (all characters up to a slash):
echo ${MYVAR##*/}
domain.com
删除文件名,留下的路径(后删除最短的匹配最后 /
)
echo ${MYVAR%/*}
users/joebloggs
得到的只是文件扩展名(最后期限前删除所有):
Get just the file extension (remove all before last period):
echo ${MYVAR##*.}
com
的注:的做两次手术,你不能将它们合并,但分配给一个中间变量。因此,要获得该文件的名称不带路径或扩展名:
NOTE: To do two operations, you can't combine them, but have to assign to an intermediate variable. So to get the file name without path or extension:
NAME=${MYVAR##*/} # remove part before last slash
echo ${NAME%.*} # from the new var remove the part after the last period
domain
这篇关于使用bash /剪切/分割提取字符串的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!