I'm fairly new to Vim and I haven't been able to find on this site how to search and replace with a varying part of a string. I need to apply a global edit to all times "SetTag("...")" appears with ... being any word. My edit is to add one more word after the second quotation mark. example: SetTag("err" + __LINE__ with the bolded part being what I need to add. Can anyone let me know how this is possible with a vim search command? Thanks!
Add a comment |
1 Answer
nb: I assume "word" is any sequence of characters other than a doublequote character. Modify as needed.
:%s/SetTag("\([^"]*\)")/SetTag("\1" + __LINE__)/ the escaped parentheses grab the sub-match; the \1 in the replacement string is replaced by that sub-match.
4 Comments
gk12345
You are right that the "word"s I have are letters and not doublequote characters but that did not work for me. This gives me
Pattern not found: SetTag("\([^"]*\)") The "word" varies between many different tag categories. By "Modify as needed" do you mean I need to enter each word individually or it would catch all words? (I am looking for a catch all.) for reference this is the exact command I ran %s/SetTag("\([^"]*\)")/SetTag("\1 line: " + std::to_string(__LINE__)/L. Scott Johnson
The modify part was just what constitutes a word. In my case I used
[^"]* to select any string of zero or more non-doublequote characters. The part inside the \(...\) is the word, the rest is supposed to be the exact surrounding text.L. Scott Johnson
If it didn't match, try just searching for it with
/ to see what parts match and when it stops matching. Maybe there's an extra space or something in your target text.gk12345
Ah I see, what broke the command I ran above was the close parenthesis when I didn't need one. Worked perfectly, thanks!