我想知道是否有可能(推薦可能是更好的詞)使用sed將URL轉換爲文檔中的HTML超鏈接。因此,它看起來喜歡的事情:使用sed將URL轉換爲HTML鏈接?
http://something.com
而且隨着
<a href="http://something.com">http://something.com</a>
任何想法取代它們?對於電子郵件地址也可以做同樣的事情嗎?
我想知道是否有可能(推薦可能是更好的詞)使用sed將URL轉換爲文檔中的HTML超鏈接。因此,它看起來喜歡的事情:使用sed將URL轉換爲HTML鏈接?
http://something.com
而且隨着
<a href="http://something.com">http://something.com</a>
任何想法取代它們?對於電子郵件地址也可以做同樣的事情嗎?
這可能會實現。
sed -i -e "s|http[:]//[^ ]*|<a href=\"\0\">\0</a>|g" yourfile.txt
它取決於URL後面跟着一個空格(情況並非總是如此)。
你可以使用類似的電子郵件。
sed -i -e "s|\[email protected]\w+\.\w+(\.\w+)?|<a href=\"mailto:\0\">\0</a>|g" yourfile.txt
那些可能會讓你開始。我建議在進行內聯更改之前先關閉-i選項以測試您的輸出。
您可以使用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>
sed -i.bakup 's|http.[^ \t]*|<a href="&">&</a>|' htmlfile
雖然你可以使用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))
就我個人而言,我發現閱讀和維護起來要容易得多。
該文件包含以下內容
下面的代碼將給 正確的輸出
sed -r 's/(.*)/\<a href="\1">\1\<\/a\>/' file
這個答案是微不足道的,沒有提供其他答案,以前給出的其他信息,甚至沒有輸出正確的HTML提供的例子(缺少引號)。 – 2010-03-22 17:07:01
現在給出正確的答案。它也會給出報價。 – muruga 2010-03-23 03:27:44
不是真的。記住OP有一個有其他文本的文檔。如果您使用(。*),則您將用其他文本替換整行。 – ghostdog74 2010-03-23 03:35:15
就像一個魅力! – polym 2016-01-30 10:32:10