如何在Sed中找到[]中的文本?

时间:2009-05-25 03:05:22

标签: regex sed

这类似于已经提出过的问题。但是,我正在寻找Sed特定的答案。我的文字类似于以下内容:

一些示例文本[带有一些额外的文字] .foo

我需要抓住括号内的文字。到目前为止,我的尝试都是徒劳的。我可以用其他工具解析这行,但我似乎无法让Sed正确地解析它。

3 个答案:

答案 0 :(得分:4)

这样的东西?

$ echo Some sample text [with some extra text].foo | sed -e 's/.*\[\([^]]*\)\].*/\1/g'
with some extra text

$ echo Some sample text [with some extra text].foo | sed -e 's/.*\[\([^]]*\)\].*/Your text was: "\1", okay?/g'
Your text was: "with some extra text", okay?

答案 1 :(得分:1)

以下是替换括号内文本的示例:

$ echo 'Some sample text [with some extra text].foo' | sed -e 's/\[\(with some extra text\)\]/<\1>/g'
Some sample text <with some extra text>.foo

答案 2 :(得分:0)

echo "Some [sample inside] text [with some extra text].foo" | sed -n '/\[/{ s/\]/\n/g; s/.[^\n]*\[/:/g;s/\..*//;p}'
:sample inside:with some extra text