2016-07-31 91 views
1

我使用Ubuntu 14.04,和我有下面的语句:sed的 - 正则表达式的方括号检测的Linux

192.168.2.4 [text to capture] Test: This is a test statement. 

我试图捕捉到“文本捕获”使用下面的正则表达式:

echo "192.168.2.4 [text to capture] Test: This is a test statement" | sed -r "s/^[^\[\]]*\[(.*)\].*$/\1/" 

正则表达式的思想是遍历所有不匹配开合方括号的字符。遇到方括号时,捕获文本直到遇到右括号,然后忽略所有后续字符。

当我在regex tester中使用上述正则表达式时,我可以看到“正在捕获的文本”正在被捕获。

然而,执行上述正则表达式的命令又名返回完整的语句:

echo "192.168.2.4 [text to capture] Test: This is a test statement" | sed -r "s/^[^\[\]]*\[(.*)\].*$/\1/" 

任何人能发现我在这里错过了什么?我相信我已经正确地脱离了字符括号,因为它与正则表达式测试程序正常工作。

感谢 约翰

回答

2

实际上,你只需要排除在第一条语句开始[

echo "192.168.2.4 [text to capture] Test: This is a test statement" | sed -r "s/^[^[]*\[(.*)\].*$/\1/" 

如果你真的想要一个[^ ]内都[]只使用[^][]和你不不需要逃跑。

4

你可以使用这个sed的:

echo "192.168.2.4 [text to capture] Test: This is a test statement" | 
sed -r 's/^[^[]*\[([^]]*)\].*$/\1/' 

text to capture 

但是为了简单起见,我建议使用awk来避免复杂的正则表达式:

echo "192.168.2.4 [text to capture] Test: This is a test statement" | 
awk -F '[][]' '{print $2}' 

text to capture 

这里是一个gnu grep替代为相同的(虽然AWK推荐):

echo "192.168.2.4 [text to capture] Test: This is a test statement" | 
grep -oP '[^][]+(?=\])' 

text to capture 
2
$ echo "192.168.2.4 [text to capture] Test: This is a test statement" | 
sed -E 's/.*\[([^]]*)\].*/\1/' 
text to capture 

如果您使用GNU-SID,注意使用无证-E选项,使扩展正则表达式

1
$ echo "192.168.2.4 [text to capture] Test: This is a test statement" | 
    sed -E 's/.*\[([^]]+).*/\1/' 
text to capture 

$ echo "192.168.2.4 [text to capture] Test: This is a test statement" | 
    sed -E 's/.*\[(.*)\].*/\1/' 
text to capture 
0

这是使用“剪切”命令,来提取括号内的文字的另一种方法在Linux中。第一个“剪切”提取在第一个方形(开头)括号之后出现的文本,而第二个剪切从第一个剪切语句的输出中提取在方形括号之前出现的文本。

echo "192.168.2.4 [text to capture] Test: This is a test statement" | cut -d"[" -f2 | cut -d"]" -f1 
text to capture 

感谢

约翰

+1

你能添加说明?就目前情况而言,目前还不清楚这是什么(它是否打算作为对问题的更新?)或者它的作用。 – Laurel