Bash script to add tags if you're reorganizing

Was browsing the forum when I found this post, about applying a template to multiple files. If you think about it, a template is just some combination of properties, which is just some markdown. So, made a quick bash script to help anyone doing a similar reorg of their notes folder!

#!/bin/bash

# Specify the directory containing markdown files.
# Replace '/path/to/markdown/files' with the actual path to your markdown files.
DIRECTORY='/path/to/markdown/files'

# Iterate over every markdown file in the specified directory.
for file in "$DIRECTORY"/*.md; do
  # Check if the file is a regular file.
  if [ -f "$file" ]; then
    # Extract the date from the filename (relevant to me since my file names were the date, which I wanted to put in the created property)
    filename=$(basename -- "$file")
    file_date="${filename%.md}"

    # Temporarily store the existing content of the file.
    temp_file=$(mktemp)
    cat "$file" > "$temp_file"

    # Write the YAML front matter to the file.
    echo "---" > "$file"
    echo "created: $file_date" >> "$file"
    echo "tags:" >> "$file"
    echo "  - note" >> "$file"
    echo "  - journal" >> "$file"
    echo "---" >> "$file"

    # Append the original content back to the file.
    cat "$temp_file" >> "$file"
    # Remove the temporary file.
    rm "$temp_file"
  fi
done

echo "YAML front matter has been added to all markdown files in $DIRECTORY."
2 Likes