Renaming Markdown Files Based on Front Matter Date Using Bash Script

Managing files with meaningful and structured names can greatly enhance organization and accessibility. Suppose you have a collection of Markdown files containing Front Matter sections, each with a “date” field. You want to rename these files using the date from their Front Matter section to create a consistent and informative naming scheme. This article will guide you through achieving this task using a bash script on macOS.

Prerequisites

  • Basic familiarity with the command line interface (CLI).
  • A macOS environment with bash, grep, awk, and date utilities.

Scenario

Let’s say you have a set of Markdown files in a folder. You want to rename these files based on the date mentioned in their Front Matter sections. Additionally, you want to exclude renaming any files named “README.md” or “template.md.”

Bash Script Implementation

Here’s the step-by-step implementation of the bash script to accomplish the renaming task:

  1. Create the Bash Script

Create a new file named rename_files.sh using your preferred text editor. Copy and paste the following script into the file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#!/bin/bash

# Loop through all .md files in the current folder
for file in *.md; do
    if [[ -f "$file" && "$file" != "README.md" && "$file" != "template.md" ]]; then
        # Read the date from Front Matter
        date=$(grep -oE '(date: )([0-9]{4}-[0-9]{2}-[0-9]{2})' "$file" | awk '{print $2}')

        # Format the date to match the desired filename format
        formatted_date=$(date -j -f "%Y-%m-%d" "$date" +'%Y-%m-%d')

        # Create the new filename
        new_filename="${formatted_date}-${file}"

        # Rename the file
        mv "$file" "$new_filename"

        echo "Renamed: $file -> $new_filename"
    fi
done
  1. Make the Script Executable

Open your terminal and navigate to the directory containing the script. Run the following command to make the script executable:

1
chmod +x rename_files.sh
  1. Run the Script

Place the script in the same directory as your Markdown files. In the terminal, execute the script using the following command:

1
./rename_files.sh

The script will loop through all .md files in the folder, excluding README.md and template.md, and rename them based on the date mentioned in their Front Matter sections.

Conclusion

Organizing files is essential for efficient management of your projects and content. By using a bash script to rename Markdown files based on the Front Matter date, you can achieve a consistent and meaningful naming convention. This approach not only helps you stay organized but also improves the clarity and relevance of your file names. With this article’s guidance, you can easily automate the renaming process and streamline your file management tasks on macOS.

0%