从括号中提取字符串

Dan*_*hoa 46 bash sed

我在bash上很新,所以这是一个非常棒的问题..

假设我有一个字符串:

string1 [string2] string3 string4
Run Code Online (Sandbox Code Playgroud)

我想string2从方括号中提取; 但是括号可能在任何其他时间围绕任何其他字符串.

我如何使用sed等来做这个?谢谢!

jma*_*man 67

试试这个:

echo $str | cut -d "[" -f2 | cut -d "]" -f1
Run Code Online (Sandbox Code Playgroud)

  • 只是为了确保我理解这里发生了什么(再次,shell脚本中的漂亮菜鸟:第一个`cut`将所有内容保存到[,第二个保存左边的所有内容];这两个一起给了我我想要的字符串. (6认同)

Dan*_*ley 58

这是使用awk的一种方式:

echo "string1 [string2] string3 string4" | awk -F'[][]' '{print $2}'
Run Code Online (Sandbox Code Playgroud)

这个sed选项也有效:

echo "string1 [string2] string3 string4" | sed 's/.*\[\([^]]*\)\].*/\1/g'
Run Code Online (Sandbox Code Playgroud)

这是sed命令的细分:

s/          <-- this means it should perform a substitution
.*          <-- this means match zero or more characters
\[          <-- this means match a literal [ character
\(          <-- this starts saving the pattern for later use
[^]]*       <-- this means match any character that is not a [ character
                the outer [ and ] signify that this is a character class
                having the ^ character as the first character in the class means "not"
\)          <-- this closes the saving of the pattern match for later use
\]          <-- this means match a literal ] character
.*          <-- this means match zero or more characters
/\1         <-- this means replace everything matched with the first saved pattern
                (the match between "\(" and "\)" )
/g          <-- this means the substitution is global (all occurrences on the line)
Run Code Online (Sandbox Code Playgroud)

  • 当然.我将在答案中添加一个解释. (4认同)

Ale*_*sky 17

纯粹的bash:

STR="string1 [string2] string3 string4"
STR=${STR#*[}
STR=${STR%]*}
echo $STR
Run Code Online (Sandbox Code Playgroud)


gho*_*g74 15

这是另一个,但它会处理多次事件,例如

$ echo "string1 [string2] string3 [string4 string5]" | awk -vRS="]" -vFS="[" '{print $2}'
string2
string4 string5
Run Code Online (Sandbox Code Playgroud)

简单的逻辑是这样,你拆分"]"并通过拆分词找到"[",然后拆分"["得到第一个字段.在Python中

for item in "string1 [string2] string3 [string4 string5]".split("]"):
    if "[" in item:
       print item.split("]")[-1]
Run Code Online (Sandbox Code Playgroud)


out*_*dev 12

使用-F'[delimiters]指定awk多个分隔

如果分隔符是方括号,请将它们背对背,就像这样] [

awk -F '[][]' '{print $2}'
Run Code Online (Sandbox Code Playgroud)

否则你将不得不逃避他们

awk -F '[\\[\\]]' '{print $2}'
Run Code Online (Sandbox Code Playgroud)

获取括号之间的值的其他示例:

echo "string1 (string2) string3" | awk -F '[()]' '{print $2}'
echo "string1 {string2} string3" | awk -F '[{}]' '{print $2}'
Run Code Online (Sandbox Code Playgroud)