删除锚标记,但保留锚文本

时间:2012-02-07 20:37:40

标签: bash unix sed

如何删除锚标记,但将锚文本保留在Bash中?所以我想删除除示例文本之外的所有内容。

<a href="http://example.com">Example text</a>

所以,如果我这样做:

echo '<a href="http://example.com">Example text</a>' | sed -e 's/<[^>]*>//g'

删除所有html。我想要删除锚标记,但也保留锚文本...在这种情况下也称为示例文本。

4 个答案:

答案 0 :(得分:5)

您可以使用以下命令:

$ echo '<a href="http://example.com">Example text</a>' | sed -e 's/<[^>]*>//g'
Example text

或者,您也可以使用perl代替sed,因为non greedy正则表达式在这里会有所帮助:

$ echo '<a href="http://example.com">Example text</a>' | perl -pe 's/\<.*?\>//g'
Example text

注意:使用正则表达式来解析HTML是discouraged,但对于这个小任务,我会说可以坚持使用命令行中的可用工具。

编辑:要删除只是锚标签,可以使用正则表达式更新如下:

sed -e 's/<\/\?a\s*[^>]*>//g'

答案 1 :(得分:1)

这是一个有用的指南: http://www.eng.cam.ac.uk/help/tpl/unix/sed.html

答案 2 :(得分:0)

如果您的输入格式正确,则可以从命令行使用XSLT。 (我建议使用Saxon,但Xalan也可以。):

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="a">
    <xsl:apply-templates/>
  </xsl:template>

</xsl:stylesheet>

另见RegEx match open tags except XHTML self-contained tags: - )

答案 3 :(得分:0)

接受的答案将从HTML中删除所有标签,而不仅仅是链接。更好的Perl命令可以删除altStr = string.Format("<altitude>{0}</altitude>", Math.Round(alt, 16)); (但不删除其他标签),同时保留锚文本,如下:

<a>..</a>

对其进行测试:

perl -pe 's/\<a [^>]*\>(.*?)<\/a>/$1/gi'

它留下了:

<html><A HREF="http://example.com/"><b>Anchor Text</b></A></html>

要仅删除包含特定URL的链接(而保留其他链接不变),可以使用:

<html><b>Anchor Text</b></html>

您可以通过在其上输入文字来使用它:

perl -pe 's/\<a [^>]*href\=\"http\:\/\/example\.com[^>]+\>(.*?)\<\/a\>/$1/gi'

或使用echo "<html>..." | perl -pe 's/...' 标志将其用于就地修改文件,以进行修改:

-i