sed remove '_ipx/xxx/' from "/_ipx/xxx/images/img.webp"

Viewed 41083

Trying to figure out the regex command using sed to replace the _ipx/xxx/ with nothing so the src ends up as just images/logo.webp.

As an example if I have the following img tag in index.html:

<img src="/_ipx/w_253,f_webp,q_80/images/img.webp"
alt="Testing a Custom Component"
sizes="(max-width: 640px) 100vw, 33vw"
srcset="/_ipx/w_640,f_webp,q_80/images/img.webp 640w, /_ipx/w_253,f_webp,q_80/images/img.webp 253w" />

I want the sed to replace it to be:

<img src="/images/img.webp"
alt="Testing a Custom Component"
sizes="(max-width: 640px) 100vw, 33vw"
srcset="/images/img.webp 640w, /images/img.webp 253w" />

According to https://regex101.com I think the following should do it: /_ipx\/.+?\//gi however when I try using it, nothing happens: sed -i '' -e 's/_ipx\/.+?\//test/gi' index.html

1 Answers

You may use this sed command:

sed 's~/_ipx/[^/]*~~g' index.html

<img src="/images/img.webp"
alt="Testing a Custom Component"
sizes="(max-width: 640px) 100vw, 33vw"
srcset="/images/img.webp 640w, /images/img.webp 253w" />

However do keep in mind that it will replace /_ipx/... everywhere not just inside few attributes.

To keep replacements only within src or srcset attributes, use:

sed -E -e ':a' -e 's~((srcset|src)="[^"]*)/_ipx/[^/]*~\1~g;ta' index.html

<img src="/images/img.webp"
alt="Testing a Custom Component"
sizes="(max-width: 640px) 100vw, 33vw"
srcset="/images/img.webp 640w, /images/img.webp 253w" />

Note that we have to use a label and jump-to feature here as we have to make sure to match and replace **within srcsetor src ** attributes only not everywhere.

Related