bash 从括号中提取字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7209629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:58:29  来源:igfitidea点击:

Extract string from brackets

bashsed

提问by Dang Khoa

I'm pretty new at bash so this is a pretty noob question..

我在 bash 方面很新,所以这是一个非常菜鸟的问题..

Suppose I have a string:

假设我有一个字符串:

string1 [string2] string3 string4

I would like to extract string2from the square brackets; but the brackets may be surrounding any other string at any other time.

我想string2从方括号中提取;但括号可以在任何其他时间包围任何其他字符串。

How would I use sed, etc, to do this? Thanks!

我将如何使用sed等来做到这一点?谢谢!

回答by jman

Try this:

尝试这个:

echo $str | cut -d "[" -f2 | cut -d "]" -f1

回答by Daniel Haley

Here's one way using awk:

这是使用 awk 的一种方法:

echo "string1 [string2] string3 string4" | awk -F'[][]' '{print }'

This sed option also works:

这个 sed 选项也有效:

echo "string1 [string2] string3 string4" | sed 's/.*\[\([^]]*\)\].*//g'

Here's a breakdown of the sed command:

这是 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
/         <-- 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)

回答by Alex Howansky

In pure bash:

在纯 bash 中:

STR="string1 [string2] string3 string4"
STR=${STR#*[}
STR=${STR%]*}
echo $STR

回答by ghostdog74

Here's another one , but it takes care of multiple occurrences, eg

这是另一个,但它处理多次出现,例如

$ echo "string1 [string2] string3 [string4 string5]" | awk -vRS="]" -vFS="[" '{print }'
string2
string4 string5

The simple logic is this, you split on "]" and go through the split words finding a "[", then split on "[" to get the first field. In Python

简单的逻辑是这样的,您在“]”上拆分并通过拆分词找到“[”,然后在“[”上拆分以获得第一个字段。在 Python 中

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

回答by outdev

Specify awk multiple delimiters with -F '[delimiters]'

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

If the delimiters are square brackets, put them back to back like this ][

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

awk -F '[][]' '{print }'

otherwise you will have to escape them

否则你将不得不逃离他们

awk -F '[\[\]]' '{print }'

Other examples to get the value between the brackets:

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

echo "string1 (string2) string3" | awk -F '[()]' '{print }'
echo "string1 {string2} string3" | awk -F '[{}]' '{print }'

回答by dawg

Another awk:

另一个awk

$ echo "string1 [string2] string3 [string4]" |
awk -v RS=[ -v FS=] 'NR>1{print }' 
string2
string4

回答by Robert Sutton

Here is an awk example, but I'm matching on parenthesis which also makes it more obvious of how the -F works.

这是一个 awk 示例,但我在括号上进行匹配,这也使 -F 的工作原理更加明显。

echo 'test (lskdjf)' | awk -F'[()]' '{print $2}'

回声'测试(lskdjf)' | awk -F'[()]' '{print $2}'

回答by Luca Davanzo

Inlinesolution could be:

内联解决方案可能是:

a="first \"Foo1\" and second \"Foo2\""
echo ${a#*\"} | { read b; echo ${b%%\"*}; }

You can test in single line:

您可以单行测试:

a="first \"Foo1\" and second \"Foo2\""; echo ${a#*\"} | { read b; echo ${b%%\"*}; }

Output: Foo1

输出:Foo1

Example with brackets:

带括号的示例:

a="first [Foo1] and second [Foo2]"
echo ${a#*[} | { read b; echo ${b%%]*}; }

That in one line:

在一行中:

a="first [Foo1] and second [Foo2]"; echo ${a#*[} | { read b; echo ${b%%]*}; }

Output: Foo1

输出:Foo1

回答by Sudhir Sinha

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 }' file
202
203
204

At the first sight, the delimiter used in the above command might be confusing. Its simple. 2 delimiters are to be used in this case: One is [ and the other is ]. Since the delimiters itself is square brackets which is to be placed within the square brackets, it looks tricky at the first instance.

乍一看,上述命令中使用的分隔符可能令人困惑。这很简单。在这种情况下将使用 2 个分隔符:一个是 [,另一个是 ]。由于定界符本身是方括号,方括号要放在方括号内,因此一开始看起来很棘手。

Note: If square brackets are delimiters, it should be put in this way only, meaning first ] followed by [. Using the delimiter like -F '[[]]' will give a different interpretation altogether.

注意:如果方括号是分隔符,则只能这样放置,意思是先是 ] 后是 [。使用像 -F '[[]]' 这样的分隔符将给出完全不同的解释。

Refer this link: http://www.theunixschool.com/2012/07/awk-10-examples-to-read-files-with.html

请参阅此链接:http: //www.theunixschool.com/2012/07/awk-10-examples-to-read-files-with.html