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
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
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"
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
Before running the script, I would recommend checking that the
findcommand 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)
On Linux, you have the
renamecommand for this: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.
More safer solution from Stack Overflow answer:
Use
-print0is necessary for processing file names with newlines.