【问题标题】:Convert URLs into HTML links using sed?使用 sed 将 URL 转换为 HTML 链接?
【发布时间】:2011-01-30 04:33:56
【问题描述】:

我想知道是否可以(推荐可能是更好的词)使用 sed 将 URL 转换为文档中的 HTML 超链接。因此,它会寻找如下内容:

http://something.com

并将它们替换为

<a href="http://something.com">http://something.com</a>

有什么想法吗?电子邮件地址也可以这样做吗?

【问题讨论】:

    标签: html command-line replace sed hyperlink


    【解决方案1】:

    你可以使用 awk

    awk '
    {
     for(i=1;i<=NF;i++){
       if ($i ~ /http/){
          $i="<a href=\042"$i"\042>"$i"</a>"
       }
     }
    } 1 ' file
    

    输出

    $ cat file
    blah http://something.com test http://something.org
    
    $ ./shell.sh
    blah <a href="http://something.com">http://something.com</a> test <a href="http://something.org">http://something.org</a>
    

    【讨论】:

      【解决方案2】:

      这可能有效。

      sed -i -e "s|http[:]//[^ ]*|<a href=\"\0\">\0</a>|g" yourfile.txt
      

      这取决于 url 后跟一个空格(并非总是如此)。

      你可以对电子邮件做类似的事情。

      sed -i -e "s|\w+@\w+\.\w+(\.\w+)?|<a href=\"mailto:\0\">\0</a>|g" yourfile.txt
      

      这些可能会让您入门。我建议在内联更改之前不要使用 -i 选项来测试您的输出。

      【讨论】:

        【解决方案3】:
        sed -i.bakup 's|http.[^ \t]*|<a href="&">&</a>|'  htmlfile
        

        【讨论】:

        • 添加-r(扩展正则表达式)更安全,否则可能会在 sed: -e expression : unterminated `s' command 上失败
        【解决方案4】:

        虽然您可以使用 sed,但我通常只会在需要只写的东西时才使用 sed(也就是说,它只需要工作而不需要维护)。

        我发现 Python 正则表达式库更易于访问(并且能够添加更强大的结构)。

        import re
        import sys
        
        def href_repl(matcher):
            "replace the matched URL with a hyperlink"
            # here you could analyze the URL further and make exceptions, etc
            #  to how you did the substitution. For now, do a simple
            #  substitution.
            href = matcher.group(0)
            return '<a href="{href}">{href}</a>'.format(**vars())
        
        text = open(sys.argv[1]).read()
        url_pattern = re.compile(re.escape('http://') + '[^ ]*')
        sys.stdout.write(url_pattern.sub(href_repl, text))
        

        就我个人而言,我发现这更容易阅读和维护。

        【讨论】:

          【解决方案5】:

          文件包含以下内容

          http://something.com

          以下代码将给出 正确的输出

          sed -r 's/(.*)/\<a href="\1">\1\<\/a\>/' file
          

          【讨论】:

          • 这个答案很简单,没有提供比之前给出的其他答案更多的信息,甚至没有为提供的示例输出正确的 HTML(缺少引号)。
          • 现在给出正确答案。它也会给出引号。
          • 并非如此。记住 OP 有一个包含其他文本的文档。如果您使用 (.*),您也将用其他文本替换整行。
          猜你喜欢
          • 2015-04-22
          • 2014-01-17
          • 2012-11-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-01-30
          • 2012-09-20
          相关资源
          最近更新 更多