Adding characters at the start and end of each line in a file

In vim, you can do

:%s/^\(.*\)$/"\1"/
  • s/regex/replace/ is vim command for search n replace.
  • % makes it apply throughout the file
  • ^ and $ denotes start and end of the line respectively.
  • (.*) captures everything in between. ( and ) needs to be escaped in vim regexes.
  • \1 puts the captured content between two quotes.

simpler:

%s/.*/"&"

Explanation: By default, a pattern is interpreted as the largest possible match, so .* is interpreted as the whole line, with no need for ^ and $. And while \(...\) can be useful in selecting a part of a pattern, it is not needed for the whole pattern, which is represented by & in the substitution. And the final / in a search or substitution is not needed unless something else follows; though leaving it out could be considered laziness. (If so, I'm lazy.)


The two answers suggesting %s are perfect, and I expect you'll learn to love %s and use it often. But if you find yourself wanting to surround other blocks of text frequently, you owe it to yourself to check out the surround.vim plugin, which would allow you to do what you asked for with the following four keystrokes: yss" And there are many other useful built-in surround targets. For example, to surround the current word with double quotes: csw", and to change the surrounding single quotes to double quotes: cs'".

surround.vim is one of my favorite vim plugins, and I use it daily.