For an initial file with lines like this example:


The desired state of the file is


I've been doing this with two commands, :%s/^/'/g and :%s/$/'/g, that I would like to get into one. However, when I try


I get the error

E486: Pattern not found: [$^]

I know the leading ^ in brackets means exclusion, so I figured putting $ first would mean match both the beginning and end of lines, which is obviously not happening.

How can I match both the beginning and end of lines in vim?

  • Avoid answering questions in comments. Jul 27, 2017 at 18:07
  • %norm I'<c-v><esc>A' Jul 28, 2017 at 5:47
  • Did any of the answers solve your problem? If so, please use the checkmark to tell the system that the question is Answered. Thank you!
    – Jeff Schaller
    Jul 30, 2017 at 12:10
  • @JeffSchaller, Aye, and thanks for following up. I'd like to give the community a few more days to provide answers before selecting the problem as solved, but I won't forget to follow through. Jul 30, 2017 at 18:37

4 Answers 4


How about:


"Replace zero or more characters with those characters preceded and succeded by a single-quote".


^ and $ do not hold those meanings (start or end of line) inside [ ], which is used for selecting a group of characters. Inside [ ], most regex operators lose their meaning (and some characters gain special meaning, or get a different meaning). A leading ^ in [] means that the group is negated - match everything except these characters. So [^$] matches on any character other than $. (And [$^] matches just the $ and ^ characters.)

If you want to match the start or end of a line, use /^\|$/, where | is or (needs to be escaped in Vim's default regex mode).



The g is needed since the ^ and $ are two independent matches, and s by default only acts on the first match in a line.


You don't really need to match the beginning and end of the line if you can just greedily match the whole thing:


The main thing to know is to escape the parenthesis to create the "capture group", then use \1 to refer back to what was captured.

  • Seems like a harder version of the accepted answer's %s/.*/'&'/g but maybe more extensible if there are several matching groups. May 6, 2018 at 11:46

With norm[al] command and A to append control, I to prepend control which we make the :exe[cute] command to execute the second prepend 'norm' since by default :norm[al]command cannot be followed by another command as in :help :normal documented.

so the command would be as below:

:exe "%norm A'" |%norm I'

Note that % here performing the changes on all lines.

  • Neat option. Not exactly a regex but it gets the job done in vim. Jul 27, 2017 at 19:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.