morissette
morissette

Reputation: 1099

Sed backreference not working properly

Test Data:

<img src=\"images/docs/mydash_grooms.png\" alt=\"\" />

Sed:

sed 's/<img\ssrc=\\"images\/docs\/\([[:graph:]]\)/<a class=\\"popup-image\\" href=\\"images\/docs\/\1\\"><img src=\\"images\/docs\/tn.\1/g' test.txt 

Output from Sed:

<a class=\"popup-image\" href=\"images/docs/m\"><img src=\"images/docs/tn.mydash_grooms.png\" alt=\"\" />

Why is my backreference not working properly both times used?

Trying to accomplish: Changing:

<img src=\"images/docs/mydash_grooms.png\" alt=\"\" />

to

<a class=\"popup-image\" href=\"images/docs/mydash_grooms.png\"><img src=\"images/docs/tn.mydash_grooms.png\" alt=\"\" />

Upvotes: 1

Views: 300

Answers (2)

potong
potong

Reputation: 58483

This might work for you (GNU sed):

sed -r 'h;s|img src(.*) alt.*|a class=\\"popup-image\\" href\1>|;G;s/\n//;s|(.*/)([^>])|\1tn.\2|' file

Save the line in the hold space then alter the line to replicate the first attribute. Append the original line and insert the tn. into the file name.

Upvotes: 0

user3520197
user3520197

Reputation:

You have to escape the \ so they become actually "\\". However, you also have to escape the /, which makes the string very complex. I suggest replacing the delimiter of sed (i.e., the '/'), to another character to avoid complex strings. For example, using @

sed 's@<img src=\\"images/docs/\(.*\)\\" alt=\\"\\" />@<a class=\\"popup-image\\" href=\\"images/docs/\1\\"><img src=\\"images/docs/tn.\1\\" alt=\\"\\" />@g' test.txt

Futhermore, please replace the [[:graph:]], it was not working for me.

Upvotes: 1

Related Questions