How to rename all md files to mdx

Emma Goto 🍙 - Nov 26 '20 - - Dev Community

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!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player