我在bash方面还比较新,所以这是一个非常初级的问题。
假设我有一个字符串:
string1 [string2] string3 string4
我想从方括号中提取string2
,但是这些方括号可能在任何其他时间包围任何其他字符串。 如何使用sed
等工具来实现?谢谢!试试这个:
echo $str | cut -d "[" -f2 | cut -d "]" -f1
以下是使用 awk 的一种方法:
echo "string1 [string2] string3 string4" | awk -F'[][]' '{print $2}'
这个sed选项也可以工作:
echo "string1 [string2] string3 string4" | sed 's/.*\[\([^]]*\)\].*/\1/g'
以下是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)
在纯 Bash 中:
STR="string1 [string2] string3 string4"
STR=${STR#*[}
STR=${STR%]*}
echo $STR
[string2]
(还要提取括号)? - Sopalajo de Arrierez使用-F '[分隔符]'指定awk多个分隔符。
如果分隔符是方括号,将它们挨在一起写,像这样][。
awk -F '[][]' '{print $2}'
否则你将不得不对它们进行转义
awk -F '[\\[\\]]' '{print $2}'
获取括号内的值的其他示例:
echo "string1 (string2) string3" | awk -F '[()]' '{print $2}'
echo "string1 {string2} string3" | awk -F '[{}]' '{print $2}'
这里有另一个解决方案,但它可以处理多个出现的情况,例如:
$ echo "string1 [string2] string3 [string4 string5]" | awk -vRS="]" -vFS="[" '{print $2}'
string2
string4 string5
这里的简单逻辑是:你需要以 "]" 为分隔符进行切割,然后在切割后的单词中找到一个 "[", 再以 "[" 为分隔符进行切割以获取第一个字段。在Python中实现如下:
for item in "string1 [string2] string3 [string4 string5]".split("]"):
if "[" in item:
print item.split("]")[-1]
这里有一个awk的例子,但我是在匹配括号上进行的,这也更加明显地说明了-F的工作原理。
echo 'test (lskdjf)' | awk -F'[()]' '{print $2}'
另一个 awk
:
$ echo "string1 [string2] string3 [string4]" |
awk -v RS=[ -v FS=] 'NR>1{print $1}'
string2
string4
Read file in which the delimiter is square brackets:
$ cat file
123;abc[202];124
125;abc[203];124
127;abc[204];124
To print the value present within the brackets:
$ awk -F '[][]' '{print $2}' file
202
203
204
x = (b + (c - d))
,那么它应该提取出 b + (c - d)
。谢谢。 - gbe内联解决方案可能是:
a="first \"Foo1\" and second \"Foo2\""
echo ${a#*\"} | { read b; echo ${b%%\"*}; }
你可以在单行中进行测试:
a="first \"Foo1\" and second \"Foo2\""; echo ${a#*\"} | { read b; echo ${b%%\"*}; }
输出:Foo1
带括号的示例:
a="first [Foo1] and second [Foo2]"
echo ${a#*[} | { read b; echo ${b%%]*}; }
一行代码实现:
a="first [Foo1] and second [Foo2]"; echo ${a#*[} | { read b; echo ${b%%]*}; }
输出:Foo1
cut
保存了左括号 [ 右侧的所有内容,第二个保存了右括号 ] 左侧的所有内容;这两个命令结合在一起给了我想要的字符串。 - Dang Khoa