I have a Markdown file with image listings as follows.

![Some Text](static/images/image.png)

Using sed, I wish to convert it to the following format, but am not able to figure the correct pattern.


A little more context. My Markdown files are like,

![Some Text](static/images/image.png)

I need to batch convert them to,


From other answers on Stackoverflow, I gathered that the pattern \[[^]]\] can be used to match square brackets. Using that, I could do the transformation i.e.

sed 's,^\!\[[^]]\+\]\(.*\)$,[]\1,g' file.md --> Works! Gives [](images/sl/2012-06-18.png)

But if I append {.my-class} towards the end, it messes it up.

sed 's,^\!\[[^]]\+\]\(.*\)$,[]\1\{.my-class\},g' file.md --> doesn't work! Gives {.my-class}(static/images/image.png)

So essentially, how can I use { in the replace pattern?

  • your last command works for me in GNU sed, even no need to escape { and }. – pLumo Oct 4 '18 at 14:47
  • Please expand on "messes up" and "doesn't work". What result do you get instead? Was there an error message? – JigglyNaga Oct 4 '18 at 15:18

You can try this sed command:

sed 's/\[[^]]\+\]/[]/;s/$/{.myclass}/' <<< '![Some Text](static/images/image.png)'
  • Thanks oliv. When run on a file, this didn't work e.g. sed <your_pattern> file.md. But works in the form you specified i.e. using a string input. Any idea why? – Mohnish Oct 3 '18 at 2:33
  • What isn't working exactly? – oliv Oct 3 '18 at 6:40
  • Executing it on a file is not working . When run on a file (as provided in my update), it doesn't perform replacement correctly. Try it on this file - gist.github.com/mohnish82/75f5e3b6e06ae6ce51c01c36bb096374 – Mohnish Oct 4 '18 at 12:09
  • works for me, but adds the class to any line, also this replaces every [...] which may not be what is expected. – pLumo Oct 4 '18 at 14:49
  • Figured the problem. The files containing CRLF line endings were producing incorrect output, while LF ones worked correctly. Applying converter pattern (s|^M$||g) fixes the issue. Thanks everyone. – Mohnish Oct 6 '18 at 1:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.