Reputation: 33
I have multiple .xml files in which I have a repeating string pattern. I want to replace each instance of that pattern with an integer starting with "1".
e.g.
Input:
APPLE is my favorite fruit. APPLE is red in color.
Expected Output:
1 is my favorite fruit. 2 is red in color.
Upvotes: 3
Views: 970
Reputation: 182331
For simple incrementing integers from 1, 2, 3, ... (or 0, 1, 2, ...) you can use the new snippet variables $CURSOR_NUMBER
or $CURSOR_INDEX
respectively.
You would still have to find a way to select all the find matches you want to replace (and so I think the extension below is better). You could use Ctrl+D to progressively select the occurrences you want or using the Find Widget:
Find: APPLE
and then Alt+Enter to select all matches and then insert a snippet like:
"Increment integer": {
"prefix": "i++",
"body": [
"${CURSOR_NUMBER}",
]
},
by typing its trigger prefix i++
and voila, all the APPLE
instances are replaced by increasing integers.
I am sure there are other extensions that can do this, but using one that I wrote this is very easy: Find and Transform.
Create this keybinding (in your keybindings.json):
{
"key": "alt+y", // whatever keybinding you want
"command": "findInCurrentFile",
"args": {
// "find": "APPLE", // actually not necessary
"replace": "${matchNumber}",
"matchCase": true // match only APPLE, not Apple
}
}
That will replace whatever word your cursor is on with the matchNumber
starting at 1. If you wanted to start at 0, use ${matchIndex}
.
If you need to specify a more complicated regex find, you can do that too.
Upvotes: 4
Reputation: 28783
With Regex Text Generator you can do this.
APPLE
instances you want, any way you like, Ctrl+D
, Selet All Occurrences
, Alt+Enter
from Find dialog.*
{{=i+1}}
Upvotes: 1