0

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!

1 Answer 1

1

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.

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

4 Comments

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__)/
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.
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.
Ah I see, what broke the command I ran above was the close parenthesis when I didn't need one. Worked perfectly, thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.