Usually to replace strings across multiple files, one simply needs to use

sed -i 's/string1/string2/g' *

However, how could I use the sed command (or anything that works, really) to replace things strings with content relative to them. For example:

<td><a href="">a</a></td>
<td><a href="">abbr</a></td>
<td><a href="">address</a></td>
<td><a href="">area</a></td>

Using the example above, what could I use to replace the text such that the result is thus:

<td><a href="HTML-EX/html/a.html">a</a></td>
<td><a href="HTML-EX/html/abbr.html">abbr</a></td>
<td><a href="HTML-EX/html/address.html">address</a></td>
<td><a href="HTML-EX/html/area.html">area</a></td>

where it is replacing the double quotes "" with the string a few characters relative to it.

2 Answers 2


The following example should work for you.

sed 's#<a href="">\(.*\)</a>#<a href="HTML-EX/html/\1.html">\1</a>#'

It first captures the text between the a tags, which is represented by the \1 variable. Then use the variable in the result string.

perl -i -pe 's|<a\hhref=\K "" (?=>([^<]+)</a>)|"HTML-EX/html/$1.html"|gx' *

Use the lookbehind and lookahed at "" and insert the requisite string inside these double quotes based on the lookahead capture.

You must log in to answer this question.

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