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.

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\+

| improve this answer | |
  • @linuxfan You're welcome. See the edit I just made for a slightly more concise version! – Rich Jul 25 '18 at 10:38
  • 1
    > :%s,^\d,3.\0 even shorter: :%s,^\d,3.& – Christian Brabandt Jul 26 '18 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.
| improve this answer | |

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.