Skip to contentKyle Macquarrie

VS Code tip: Match all lines starting with a certain string

Sometimes you want to batch-edit files to remove certain lines, where you know what the line starts with but not how it ends. In my case I had a legacy slug value in the frontmatter of a bunch of Markdown files, like this:

title: A Cool Post
slug: a-cool-post
description: A brief summary of the cool post

I didn’t want to have to remove that by hand in 60+ files, so I figured there had to be a way to use the regex mode in VS Code’s find & replace to do it. I am far from fluent in regular expressions, so it took me a little while to work this out, and I’m posting it here to refer back to in future, if nothing else.

A screenshot of the VS Code search panel using the regex

Using e.g. slug: (.*)\n will match every line beginning with slug: , up to and including the new line character.

Then you can replace with an empty string to remove the line.

If you omit the \n and do the same, it leaves an empty line, which I really wanted to avoid.

You can test-drive this on regex101.com.

← All articles