【问题标题】:How to solve this sed syntax issue如何解决这个 sed 语法问题
【发布时间】:2016-04-11 21:08:01
【问题描述】:

我编写了一个正则表达式代码来从一个 html 文件中提取锚标记并得到这个输出。

mdlinks.txt
    <a href='/aspnet/aspnet_refhtmlcontrols.asp'>ASP.NET Reference</a>
    <a href='/aspnet/webpages_ref_classes.asp'>Razor Reference</a>
    <a href='/html/html_examples.asp'>HTML Examples</a>
    <a href='/css/css_examples.asp'>CSS Examples</a>
    <a href='/w3css/w3css_examples.asp'>W3.CSS Examples</a>
    <a href="/js/js_examples.asp" target="_top">JavaScript Examples</a>
    <a href="/js/js_dom_examples.asp" target="_top">HTML DOM Examples</a>

我必须将输出表示为

使用 sed 工具“显示文本”。

    <a[\s]href=('|")([^>]+)">((?:.(?!\<\/a\>))*.)<\/a>

这是我的正则表达式,它捕获文本和 href 链接。

这是我写的 sed 命令

sed -E "s/\"<a[\s]href=('|\")([^>]+)\">((?:.(?!\<\/a\>))*.)<\/a>\"/\[\2\] \(\1\)/" mdlinks.txt

但这给了我错误。 有人能帮帮我吗?

【问题讨论】:

  • 你得到什么错误?期望的输出是什么样的?
  • 您正在尝试使用一些 sed 或任何其他标准 UNIX 工具(可能是 PCRE?idk)不支持的正则表达式变体。发布minimal reproducible example,以便我们为您提供帮助。
  • 您不能将非捕获组 (?: ) 与 sed 一起使用。

标签: regex linux bash sed


【解决方案1】:

这不是正则表达式(或任何其他字符串操作工具)的工作。您需要能够解析 html 的工具。一个使用xsltproc的例子:

1) 安装xsltproc 包(如果需要)

2) 编写这个描述如何转换 html 输入的 xsl 文件:stylesheet.xsl

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version= "1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" encoding="UTF-8"/>
    <xsl:template match="//a">[<xsl:value-of select="text()"/>] (<xsl:value-of select="@href"/>)</xsl:template>
</xsl:stylesheet>

3) 将您的原始文件或原始 html 内容放入变量中(比如说“CONTENT”),而不是 mdlinks.txt(此步骤无用,并且在 html 内容中查找链接容易出错且浪费时间(至少 5 小时))并写下:

xsltproc --html --novalid stylesheet.xsl <(echo "$CONTENT")

您获得:

[Google.com] (http://google.com)
[An Example] (http://example.com/files.html)
[File #23] (file23.html)
[See my picture!] (images/mypic.png)
[Email Joel] (mailto:joelross@uw.edu)

链接:http://scott.dd.com.au/wiki/XSLT_Tutorial

【讨论】:

    【解决方案2】:

    使用面向行的工具解析 html 通常会失败。鉴于您的简单布局,您可以尝试

    tr -s "<" ">" < mdlinks.txt | cut -d">" -f3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-20
      • 2014-10-07
      • 1970-01-01
      • 2019-03-25
      • 2019-04-20
      • 2011-06-07
      相关资源
      最近更新 更多