0

I have a bunch of URL in a text file. As Firefox seems unable to load these URL directly, I must convert them to HTML.

Trying with sed doesn't work:

sed -e 's/^(.*)$/<a href="\1">\1<\/a><br>/g' myfile.txt

Error message returned (translated, it may not look exactly so on english systems):

sed: -e expression n°1, char 33: invalid reference \1 in right side of the command `s'

I simply wonder why?

URLs are like so:

https://unix.stackexchange.com/questions/378496/sed-to-replace-text-url-to-html-url

some may contain these char: % & / \ _ - = :

And it seems I got a "linebreak" char at the end of the line, before the real line break, so included in the .* statement. It should be because the file was created under a Windows environment.

1
  • please add a sample of URLs you have and its HTML format.
    – Eng7
    Jul 14, 2017 at 15:44

2 Answers 2

3

If you want to group parts of an regex, either use \(\) or use extended regular expression syntax by providing the -E option to sed.

In your case it's not needed at all, as for the whole match you can use & in the replacement:

sed 's/.*/<a href="&"><\/a><br>/' myfile.txt

Note that you can also drop the ^ and $ as the greedy * makes the match cover the whole line.

4
  • 1
    g is also not needed because you've already selected the whole line with .* and if by any chance the URL's are separated by space rather than new lines which g in your code assumes, this code will not work as you have replaced the whole line without considering space as a delimiter. Jul 14, 2017 at 16:00
  • it seems to work except for the extra newlines.
    – s.k
    Jul 14, 2017 at 16:00
  • 1
    @GypsyCosmonaut Thank you, removed the g. s.k., what extra newlines? This is not supposed to add newlines. If your file has empty lines, you may drop them with sed -n 's/^http.*/<a href="&"><\/a><br>/p' myfile.txt, ignoring lines that don't start with http
    – Philippos
    Jul 14, 2017 at 16:11
  • (one & missing: ..../<a href="&">&<\/a><br>/ )
    – JJoao
    Jul 14, 2017 at 16:24
-1

You are using / in your sed expression as a separator, capturing text with /, so it fails.

Try 's@^(.*)$@<a href="\1">\1<\/a><br>@g', assuming there are no mailto links you want to convert ;-)

You could also use 's!^(.*)$!<a href="\1">\1<\/a><br>!g'

1
  • No, the slash is correctly escaped by the backslash. This was not the cause of the problem.
    – Philippos
    Jul 14, 2017 at 15:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .