Tuesday 28 April 2020

Prepend to every line in Visual Studio Code

Problem:

I want to add a string to the beginning of every line in a selection of code or text.

For example, I am reformatting what used to be a liquid templating list to a YAML list, e.g.

From:

item1
item2
item3

To:

  - item1
  - item2
  - item3


One solution - overview:

There are many ways to prepend to code quickly in bulk. One of the more versatile ways is by using the replace tool in Visual Studio Code combined with regex (i.e. regular expressions).

The "find" field will have the caret character ^ which indicates the beginning of a line. The "replace" field will have whatever you want to add at the beginning of lines.

Example:

For example, if I have the code in the screenshot below that I want to prepend the string " - " to:

First, select the code to prepend to:

Then invoke the "replace" tool:

Make sure you select the option to replace in your selection only. Then use a regex search for "^" as the beginning of a line, and replace with what you want to prepend. Do this for each line one by one until you have the results you desire.

After you are done, the lines should now be prepended with the desired string.



Notes:

There are many other ways that you can prepend lines in Visual Studio Code. The how-to above shows the regex replace method because it's a powerful tool that can handle many scenarios, not just prepending to lines.

Other methods may include installing plugins, using Visual Studio's multi-line cursor/select tools, etc.

References:

No comments:

Post a Comment