Convert Markdown Images to Hugo Shortcode

There is a pretty big flaw in Hugo workflow if you like to use Markdown editors with visual preview: images. When I paste a screen shot in the editor it is automatically saved as ./static/images/image-yyyymmddhhmmss.png in my blog directory and I see it in the editor right away. But for pretty representation I want images to be enclosed in a specially-formatted Hugo shortcode, losing the ability to preview the post visually.

So the goal is to turn this:
![image-20191017135938123](../static/images/image-20191017135938123.png)
into this:

{{< img src="image-20191016125116837.png" alt="image-20191016125116837.png"  >}}

before running Hugo to rebuild the /public directory

Here are simple commands to achieve this:

sed -i -e 's/\!\[.*\](\.\.\/static\/images\//\{\{< img src\=\"/g' *.md
sed -i -e 's/.png" >}}/\.png" \>\}\}/' *.md
sed -i -e 's/.jpg" >}}/\.jpg" \>\}\}/' *.md

The code above is a picture, because Hugo can not parse it’s own shortcodes in fenced code blocks

  • -i means “in place” with an empty string in parentheses to make sure sed does not create backups in the same folder. This is a caveat for MacOS/Linux users - sed syntax is different between platforms, for Linux you should use sed -i -e ... without empty parentheses.
  • -e is the command we want to run (the command is also enclosed in single parentheses). command format:
    s = substitute
    /pattern_to_find/pattern_to_replace_with/
    g = globally
  • *.md - in all files in current directory with .md extension

We will add these commands to the build stage of our GitLab CI template (this is only a part of the template):

script:
  - hugo version
  - echo "Start replacing image brackets"
  - ls -a
  - cd ./content
  - ls -a
  - sed -i -e 's/\!\[/\{\{\< img src\=\"/g' *.md
  - sed -i -e 's/\](\.\.\/static\/images\//.png\" alt\=\"/' *.md
  - sed -i -e 's/.png" >}}/\.png"  \>\}\}/' *.md
  - cat "Convert Markdown images to Hugo shortcode.md"
  - cd ../
  - echo "Finished replacing image brackets"
  - hugo
  - echo "Build completed"

Note the difference in sed syntax - GitLab CI will fail if you use MacOS syntax (naturally)

If everything is going as planned, the build job will finish successfully

This post is a part of a series on how to set up an automated CD pipeline for AWS-hosted static site.

May 29, 2021   (v.0897ea6)