Here is a Python script that should do what you're asking for. It uses the os module to iterate over files in a directory and the re module to find and replace instances of the tag strings.
Please replace directory_path with your actual directory path.
import os
import re
# directory path
directory_path = '/path/to/your/directory'
# iterate over all files in the directory
for filename in os.listdir(directory_path):
# check if this is a .md file
if filename.endswith('.md'):
# construct full file path
file_path = os.path.join(directory_path, filename)
# open the file
with open(file_path, 'r+') as file:
# read the file content
content = file.read()
# find all instances of tags
tags = re.findall(r'#(\w+)', content)
if tags:
# construct the new tag string
new_tags = '\n'.join(f' - {tag}' for tag in tags)
new_tags = f'---\ntags:\n{new_tags}\n---'
# replace the old tags with the new tag string
content = re.sub(r'#(\w+)', '', content).strip()
content = f'{new_tags}\n\n{content}'
# rewrite the file with the new content
file.seek(0)
file.write(content)
file.truncate()
This script works by finding all instances of hashtags in the content of each .md file. It then constructs the new tag string and replaces the old tags with it.
This script assumes that the tags are all one-word and that there are no other uses of hashtags in the file. If the tags can contain multiple words or there are other uses of hashtags, you would need to adjust the regular expression used to find the tags.