使用正则表达式用 sed 解析括号 [英] Parsing of parenthesis with sed using regex
问题描述
我在 sed
中寻找一个命令来转换这个输入流:
I am looking for a command in sed
which transforms this input stream:
dummy
(key1)
(key2)dummy(key3)
dummy(key4)dummy
dummy(key5)dummy))))dummy
dummy(key6)dummy))(key7)dummy))))
进入这个:
key1
key2
key3
key4
key5
key6
key7
其中 dummy
可以是任何不带括号的字符串.所以我基本上想提取括号之间的字符串并每行输出一个字符串.可以有额外的右括号 )
.
where dummy
can be any string without parenthesis. So I basically would like to extract the strings in-between the parenthesis and output one string per line. There can be extra closing parenthesis )
.
我使用正则表达式对 sed
进行了许多测试,但我不知道如何解决这个问题呢.虽然我确信这是可能的.(例如,我对 Perl 或 Python 等替代工具持开放态度)
I ran many tests with sed
using regex, but I can't figure out
how to solve this problem. Though I am sure it is possible.
(I am open to alternative tools like Perl or Python for instance)
括号之间的字符串 (key1, key2 .. key7) 可以是任何没有括号的字符串.
EDIT : The string between parenthesis (key1, key2 .. key7) can be any string without parenthesis.
推荐答案
你可以在 grep -oP
中使用这个基于后视的正则表达式:
You can use this lookbehind based regex in grep -oP
:
grep -oP '(?<=\()[^)]+' file
key1
key2
key3
key4
key5
key6
key7
或者使用awk
:
awk -F '[()]' 'NF>1{for(i=2; i<=NF; i+=2) if ($i) print $i}' file
key1
key2
key3
key4
key5
key6
key7
这篇关于使用正则表达式用 sed 解析括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!