1

honestly bemused and I didn't expect to be asking this but here goes.

In side VIM, and only VIM, I want to perform a global search and replace. My target text is:

51099 analgesic 43045 analgesic 70145 analgesic 52338 analgesic 41214 55309 34373 47003 50659 51327 

This goes on for several thousand lines. For all those lines that do not end "\tanalgesic" (notice the tab), I would like to retain the number and insert "\tanalgesic". I've tried several ways, none of which works (obviously).

Outside of VIM (in a general regex checker), [0-9]+$ finds all instances of "one or more digits and the end of the line". Within VIM, this does not work (:/ will have been added to represent moving into command mode then "/" for a search). I'm so baffled by why this should be the case.

Although this does not work, I expect the solution is going to look similar:

:%s/[0-9]+$/(1)\tanalgesic/g 

2 Answers 2

2

You could use for example vim very magic mode with \v

Use \1 for a backreference to group 1.

:%s/\v(\d+$)/\1\tanalgesic/g 

The command without very magic mode, with escaped parenthesis for the group, and the escaped plus sign for the quantifier:

%s/\([0-9]\+$\)/\1\tanalgesic/g | | | | | | | | | ^ All occurrences | | | ^^ Backreference to group 1 | | ^^ Escaped plus sign | ^^ Escaped parenthesis for group 1 ^ Substitute in whole file 

Output

51099 analgesic 43045 analgesic 70145 analgesic 52338 analgesic 41214 analgesic 55309 analgesic 34373 analgesic 47003 analgesic 50659 analgesic 51327 analgesic 

See http://vimregex.com/ for more information.

Sign up to request clarification or add additional context in comments.

2 Comments

That worked! Thanks. Honestly, I was struggling with this. A bit embarrassing.
@AnthonyNash Not at all, glad to help you.
0

A very specific regex that match exactly what stated at first post is:

:%s/\(^\(\(.*analgesic.*\)\@!.\)*$\)/\1\tanalgesic 

This part ^\(\(.*analgesic.*\)\@!.\)*$ match all lines that not contains analgesic word.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.