Convert urls to html links using sed?

I am wondering if it is possible (recommended, perhaps the best word) to use sed to convert URLs to HTML hyperlinks in a document. Therefore, he will look for things like:

http://something.com

And replace them with

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

Any thoughts? Can you do the same for email addresses?

+3
source share
5 answers

It might work.

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

It depends on which URL is followed by a space (which is not always the case).

You can make similar emails.

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

Those can start. I suggest abandoning the -i option to test your output before making changes to the line.

+3

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

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))

, .

0

http://something.com

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

Source: https://habr.com/ru/post/1737973/


All Articles