I’m looking for a way to find and replace text only within the YAML front matter in Obsidian markdown files.
The YAML front matter begins and ends with —, like this:
tags: activities, mac
I’m thinking this is beyond the power of regex. You need to select the text between the two “—” and then do a find/replace within that selection. It seems like some app would have to drive this–and be able to do it for all files in a folder.
I’ve written BBEdit tech support, and will post here if I learn anything from them.
Can you talk more about why you need to limit the find and replace to the YAML header? My approach when doing this on my files is to regex for each key one at a time: ^tags:(.*) and do replacements that way.
I only have those key words with a colon after them in my YAML front matter, so there isn’t a concern with replacing “tags” elsewhere in the file.
I was thinking that this YAML question was just one (real) example of the larger question: Is there a way to do a search/replace between ANY two strings, anywhere in a file?
In this YAML case, you’ve shown me that it is simpler, since anything in the header will begin the line with a word followed by a colon. In your example: ^tags:(.*), where do I put the string I want to replace on the Tags: line?
Specifically, I mistakenly put # before each tag, then later learned you don’t use the hash for tags in YAML, so I want to delete hashes in the header, but not elsewhere in the file, which would of course trash all the headings.
@rbanks88 If you want to use BBEdit to selectively remove all hashtags from a tags: line in a YAML header without removing any hashtags from any other YAML line or the note body, enter the following in the BBEdit search dialog:
Make sure you backup your notes before running any search/replace actions.
You need to run the above search/replace action multiple times – as many times as you have tags in a single tags: line.
As an example, run the above search/replace action twice to clean this sample note:
--- # YAML comment
foo: bar, baz # another YAML comment
- Russell Banks
- Matthias Steffens
tags: #tag1, #tag2
# heading 1
Some text and an inline tag: #tag3
## heading 2
Some more text containing a MultiMarkdown citekey ([#Banks2022]).
This would convert the line tags: #tag1, #tag2 in the above sample note to tags: tag1, tag2 with any other content being left untouched.
The above search/replace pattern would also work with multiple YAML blocks in the same note, and also with a multi-file search in BBEdit.