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

4
我想知道是否可以(建议使用更好的词汇)使用sed将文档中的URL转换为HTML超链接。 因此,它会寻找类似以下的内容:
http://something.com

将它们替换为

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

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

5

这可能有效。

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选项以测试输出。


2

文件包含以下内容

http://something.com

以下代码将会给出正确的输出结果

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

这个答案很琐碎,没有提供任何其他之前给出的答案所没有的信息,甚至对于所提供的示例都没有输出正确的HTML(缺少引号)。 - Jason R. Coombs
现在它会给出正确的答案,同时也会给出引号。 - muruga
不是真的。记住 OP 有一个包含其他文本的文档。如果你使用(.*),你将替换整行和其他文本一起。 - ghostdog74

1
sed -i.bakup 's|http.[^ \t]*|<a href="&">&</a>|'  htmlfile

最好加上 -r(扩展正则表达式),否则可能会出现 sed:-e expression:unterminated `s' command 的错误。 - Noam Manos

0

你可以使用 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>

-1

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

个人而言,我觉得这样更易于阅读和维护。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接