Home > other >  Sed to convert absolute to relative link in markdown file
Sed to convert absolute to relative link in markdown file

Time:10-12

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: ![alt text](https://github.com/a/b/c..../images/sample.png)

Should be replaced with: ![alt text](images/sample.png)

I thought of the following steps:

  1. Identify lines starting with ![ (ignoring the corner cases)
  2. Traverse over the text in ()
  3. Replace everything before 2nd last / with empty string

How can I implement it or any other better approach using sed?

CodePudding user response:

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).
  • Related