【问题标题】:Easiest method for removing html/xml <tags> from single-line output从单行输出中删除 html/xml <tags> 的最简单方法
【发布时间】:2012-06-12 00:00:20
【问题描述】:

我正在尝试清理的 grep 输出如下所示:

<words>Http://www.path.com/words</words>

我尝试过使用...

sed 's/<.*>//' 

...删除标签,但这只会破坏整行。我不确定为什么会这样,因为每个 '' 结束。

最简单的方法是什么?

谢谢!

【问题讨论】:

  • Grep 默认是贪婪的,这意味着它将获取第一个 &lt; 和最后一个 &gt; 之间的所有内容。

标签: html xml sed


【解决方案1】:

为你的 sed 表达式试试这个:

sed 's/<.*>\(.*\)<\/.*>/\1/'

表达式的快速细分:

<.*>   - Match the first tag
\(.*\) - Match and save the text between the tags   
<\/.*> - Match the end tag making sure to escape the / character  
\1     - Output the result of the first saved match 
       -   (the text that is matched between \( and \))

更多关于反向引用

为了完整起见,cmets 中出现了一个可能应该解决的问题。

\(\) 是 Sed 的反向引用标记。它们会保存一部分匹配的表达式以供以后使用。

例如,如果我们有一个输入字符串:

这里面有(括号)。另外我们可以像这样使用parensparens 使用反向引用。

我们开发一个表达式:

sed s/.*(\(.*\)).*\1\\(.*\)\1.*/\1 \2/

这给了我们:

parens like this

这到底是怎么回事?让我们分解表达式来找出答案。

表达式分解:

sed s/ - This is the opening tag to a sed expression.
.*     - Match any character to start (as well as nothing).
(      - Match a literal left parenthesis character.
\(.*\) - Match any character and save as a back-reference. In this case it will match anything between the first open and last close parenthesis in the expression.
)      - Match a literal right parenthesis character.
.*     - Same as above.
\1     - Match the first saved back-reference. In the case of our sample this is filled in with `parens`
\(.*\) - Same as above.
\1     - Same as above.
/      - End of the match expression. Signals transition to the output expression.
\1 \2  - Print our two back-references.
/      - End of output expression.

如我们所见,括号(())之间的反向引用被替换回匹配表达式,以便能够匹配字符串 parens

【讨论】:

  • 好的,效果很好。不过,我真的不明白它在做什么。我看到它正在转义一些字符,但是有人可以解释一下正在发生的事情(特别是括号和数字 1)吗?非常感谢!
  • @user115360 我添加了表达式细分。这能回答你的问题吗?
  • 我喜欢添加的解释。
  • 您已经回答了这个问题。谢谢!
  • 使用这部分\(.*\),您可以评论它保存文本。当您保存时,这在实践中意味着什么?我在想这可能是一个分组。但后来我意识到你正在逃避两者。那到底是在做什么呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-02
相关资源
最近更新 更多