DEV Community

Cover image for How to rename all md files to mdx
Emma Goto 🍙
Emma Goto 🍙

Posted on • Originally published at emgoto.com on

How to rename all md files to mdx

Recently I converted my Gatsby blog from Markdown to MDX, and I wanted to convert all my .md files over to .mdx for consistency’s sake.

The folder structure of my repository looks something like this:

posts
    post-slug-one
        index.md
    post-slug-two
        index.md
Enter fullscreen mode Exit fullscreen mode

Since I have over 50 posts, I didn’t want to do the renaming manually!

If you’re using VSCode, there is a Batch Rename extension you can use. However, it doesn’t seem to work when all your files are located inside of their own folders (like mine are).

I came across this snippet:

for file in *.md; do mv "$file" "${file%.md}.mdx"; done
Enter fullscreen mode Exit fullscreen mode

This seems to do the trick for any files that live in the same folder.

To get all files that live underneath the posts directory, this works:

find posts -type f -name "*.md"
Enter fullscreen mode Exit fullscreen mode

The solution

Putting both of the above snippets together, I came up with this:

find posts -type f -name "*.md"|while read file;
  do mv "$file" "${file%.md}.mdx";
done
Enter fullscreen mode Exit fullscreen mode

Before running the script, I would recommend checking that the find command is finding all the files you expect it to. Also, make sure to stash any other changes on your repository so that you can easily reverse this operation if it goes wrong!

Top comments (2)

Collapse
 
moopet profile image
Ben Sinclair

On Linux, you have the rename command for this:

rename .md  .mdx *.md
Enter fullscreen mode Exit fullscreen mode

You can probably get it on MacOS with a bit of homebrew hackery, but it's not the "rename" package on there as I just figured out.

Collapse
 
bestspacejam_34 profile image
bestspacejam

More safer solution from Stack Overflow answer:

find ./posts -name '*.md' -print0 \
  | sed -z 'p;s/md$/mdx/' \
  | xargs -0rn2 mv --
Enter fullscreen mode Exit fullscreen mode

Use -print0 is necessary for processing file names with newlines.