bash 使用 sed 提取大括号中的子字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27057032/
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
Using sed to extract a substring in curly brackets
提问by TheMightyLlama
I've currently got a string as below:
我目前有一个字符串如下:
integration@{Wed Nov 19 14:17:32 2014} branch: thebranch
This is contained in a file, and I parse the string. However I want the value between the brackets {Wed Nov 19 14:17:32 2014}
这包含在一个文件中,我解析了该字符串。但是我想要括号之间的值{Wed Nov 19 14:17:32 2014}
I have zero experience with Sed, and to be honest I find it a little cryptic.
我对 Sed 的经验为零,老实说,我觉得它有点神秘。
So far I've managed to use the following command, however the output is still the entire string.
到目前为止,我已经设法使用以下命令,但是输出仍然是整个字符串。
What am I doing wrong?
我究竟做错了什么?
sed -e 's/[^/{]*"\([^/}]*\).*//'
采纳答案by Avinash Raj
To get the values which was between {
, }
要获得介于 之间的值{
,}
$ sed 's/^[^{]*{\([^{}]*\)}.*//' file
Wed Nov 19 14:17:32 2014
回答by Jotne
This is very simple to do with awk
, not complicate regex.
这很简单awk
,而不是复杂的正则表达式。
awk -F"{|}" '{print }' file
Wed Nov 19 14:17:32 2014
It sets the field separator to {
or }
, then your data will be in the second field.
它将字段分隔符设置为{
或}
,那么您的数据将位于第二个字段中。
FS
could be set like this to:
FS
可以这样设置:
awk -F"[{}]" '{print }' file
To see all field:
查看所有字段:
awk -F"{|}" '{print "field#1=""\nfield#2=""\nfield#3="}' file
field#1=integration@
field#2=Wed Nov 19 14:17:32 2014
field#3= branch: thebranch
回答by nu11p01n73R
This might work
这可能有效
sed -e 's/[^{]*\({[^}]*}\).*//g'
Test
测试
$ echo "integration@{Wed Nov 19 14:17:32 2014} branch: thebranch" | sed -e 's/[^{]*{\([^}]*\)}.*//g'
Wed Nov 19 14:17:32 2014
2014 年 11 月 19 日星期三 14:17:32
Regex
正则表达式
[^{]*
Matches anything other than the{
, That isintegration@
([^}]*)
Capture group 1\{
Matches{
[^}]*
matches anything other than}
, That isWed Nov 19 14:17:32 2014
\}
matches a}
.*
matches the rest
[^{]*
匹配除 之外的任何内容{
,即integration@
([^}]*)
捕获组 1\{
火柴{
[^}]*
匹配除 之外的任何内容}
,即Wed Nov 19 14:17:32 2014
\}
匹配一个}
.*
匹配其余的
回答by user6093493
Simply, below command also get the data...
简单地说,下面的命令也获取数据......
echo "integration@{Wed Nov 19 14:17:32 2014} branch: thebranch" | sed 's/.*{\(.*\)}.*//g'