代码之家  ›  专栏  ›  技术社区  ›  Mike Crittenden

使用sed将url转换为HTML链接?

  •  3
  • Mike Crittenden  · 技术社区  · 16 年前

    http://something.com
    

    并用

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

    5 回复  |  直到 16 年前
        1
  •  5
  •   Jason R. Coombs    16 年前

    这可能有用。

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

    你可以用类似的方法来处理电子邮件。

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

    这些也许能让你开始。我建议在进行内联更改之前,不要使用-I选项来测试输出。

        2
  •  1
  •   ghostdog74    16 年前
    sed -i.bakup 's|http.[^ \t]*|<a href="&">&</a>|'  htmlfile
    
        3
  •  1
  •   muruga    16 年前

    该文件包含以下内容

    http://something.com

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

    sed -r 's/(.*)/\<a href="\1">\1\<\/a\>/' file
    
        4
  •  0
  •   ghostdog74    16 年前

    你可以用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>
    
        5
  •  -1
  •   Jason R. Coombs    16 年前

    虽然您可以使用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))