Issue
I got a couple of markdown files and I need to replace the absolute link to relative link for the images present in it.
Assumptions:
- The image syntax is only in markdown, i.e.
![]()
and not HTML or any other format - All the image paths ends in the image directory,
abc/xyz/images/sample.png
Example:
Absolute link:

Should be replaced with:

I thought of the following steps:
- Identify lines starting with
![
(ignoring the corner cases) - Traverse over the text in
()
- Replace everything before 2nd last
/
with empty string
How can I implement it or any other better approach using sed
?
Solution
Try with this, which implements the logic you outlined:
sed 's|\(!\[[^]]\+](\)[^)]\+/\([^)]\+/[^)]\+)\)|\1\2|' input
Using the -E
option saves just a few characters:
sed -E 's|(!\[[^]]+]\()[^)]+/([^)]+/[^)]+\))|\1\2|' input
As regards -E
, it looks like it's POSIX:
-E, -r, --regexp-extended
use extended regular expressions in the script (for portability use
POSIX -E).
Answered By - Enlico