2

Should be straight-foward but cannot get it working. I have a text file that has numbers at the beginning of some lines. For e.g:

1. Some text....
running to many lines
2. Some more text ...
3. A long line...
that spans...
many more..
lines

I'd like to add a prefix 3. to each of the numbers.

%s,^\d\+,3\.\1,g

doesn't work.

2 Answers 2

5

Firstly, you don't need to escape the dot in the replacement section (because in that part of the command it doesn't have another possible meaning).

However, that's not the cause of your problem, which is instead that you're using \1 (the first captured group), but your expression doesn't contain any groups.

You can fix this either by adding one:

:%s,^\(\d\),3.\1

Or more simply by using \0 (the entire match) instead:

:%s,^\d,3.\0

Note also that the g flag is unnecessary and so is the \+ repeat. Your expression can only match at the start of the line, so there can only ever be a single match to replace. And ^\d will match the correct position in e.g. "30." just as well as ^\d\+

2
  • @linuxfan You're welcome. See the edit I just made for a slightly more concise version!
    – Rich
    Jul 25, 2018 at 10:38
  • 1
    > :%s,^\d,3.\0 even shorter: :%s,^\d,3.& Jul 26, 2018 at 12:15
3

You can do this with

:%s/^\ze\d/3.

From :h /\ze

\ze Matches at any position, and sets the end of the match there: The
    previous char is the last char of the whole match. |/zero-width|
    Can be used multiple times, the last one encountered in a matching
    branch is used.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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