""" Fixes tags that were converted to links during Obsidian import. Specifically, it is the first 3 line and the line contains "tags:", convert all [[tag name]] to #tag-name """ import os import re from pathlib import Path DIR = '/Users/eugeneya/obsidian-vault/' double_square = re.compile("\[\[(.*?)\]\]") for file_i, path in enumerate(Path(DIR).glob('*.md')): file_name = str(path).split("/")[-1] file_handler = open(path) for line_i, line in enumerate(file_handler): if line_i < 2 and ('tags:' in line or 'tag:' in line): tag_line = line tags = double_square.findall(line) if tags: print(f'file {file_i}: {file_name}') new_tag_line = '- tags:: ' for tag in tags: new_tag_line += f'#{tag.replace(" ", "-")} ' new_tag_line += '\n' print(new_tag_line) # Save Markdown file with new local file link as a temp file # If there is already a temp version of a file, open that. temp_file_path = DIR + '/temp_' + file_name if os.path.exists(temp_file_path): full_read = open(temp_file_path, errors='ignore') else: full_read = open(path, errors='ignore') data = full_read.read() data = data.replace(tag_line, new_tag_line) with open(temp_file_path, 'wt') as temp_file: temp_file.write(data) if os.path.exists(temp_file_path): os.replace(temp_file_path, path) full_read.close() if line_i >= 2: break file_handler.close()