Published on
Last Updated on
Estimated Reading Time: 1 min
Problem
As part of the migration from Gatsby to Statiq, I had to rename all the files with the extension mdx to md.
For the posts, the mdx file lived in a directory structure similar to posts/yyyy/yyyy-mm-dddd-slug/index.mdx. I wanted to updated this to posts/yyyy/yyyy-mm-dddd-slug/slug.md.
Now, I could do it one by one or find a utility but using a single command is more elegant.
Solution
You can start using the REN (rename) command to update the filename to the parent directory name.
for /r %%F in (*.mdx) do (
for %%A in ("%%F\..") do (
ren "%%F" "%%~nxA.mdx
)
)"
Let's unpack this command.
- Line 1: Loops through all the MDX files recursively and set the value to a parameter.
- Line 2: Loop through the parent directory for the MDX file.
- Line 3: renames the MDX file to the parent directory name.
- ~nxA: Expands the value stored in parameter A to a filename and extension
As an example this will rename a file in posts/yyyy/yyyy-mm-dddd-slug/index.mdx to posts/yyyy/yyyy-mm-dddd-slug/yyyy-mm-dddd-slug.mdx.
This is not exactly what we wanted, so let's use another REN command.
for /r %%F in (*.mdx) do (
ren "%%F" "///////////*.md
)"
Let's unpack this command.
- Line 1: Loops through all the MDX files recursively and set the value to a parameter.
- Line 2: Renames the file to .md. The / drops 1 character from the filename. The number of slashes maps to yyyy-mm-dddd in the file name.
As an example this will rename a file in posts/yyyy/yyyy-mm-dddd-slug/yyyy-mm-dddd-slug.mdx to posts/yyyy/yyyy-mm-dddd-slug/slug.md.