19

I try to create a simple regex-find and replace task in Visual Studio Code.

Currently I copy from the AD some Users to a temporary file in Visual Studio code and remove the "CN=" at the beginning of the line and all the aditional informations after the first "," (regex: ,.*$). This works fine with Find&Replace in VSCode but I have manually to type it in every time I want to remove this.

So the question is, is it possible to automate this kind of task? I know there are some external tools (https://code.visualstudio.com/docs/editor/tasks) but I'm struggling to get it working...

Edit: Example requested (my regex is working, that's not the problem:/. I need an example how to automate this task... )

EXAMPLE

CN=Test User,OU=Benutzer,OU=TEST1,OU=Vert,OU=ES1,OU=HEADQUARTERS,DC=esg,DC=corp

Expected Output

Test User
Oskar
  • 293
  • 1
  • 2
  • 8

4 Answers4

17

This extension does the job:

https://marketplace.visualstudio.com/items?itemName=joekon.ssmacro#overview

It seems like the regex adheres to:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

Example

Create a file regex.json:

[{
    "command": "ssmacro.replace",
    "args": {
        "info": "strip out EOL whitespace",
        "find": "\\s+$",
        "replace": "",
        "all": true,
        "reg": true,
        "flag": "gm"
    }
}]

"info" is just a reminder, doesn't do anything.

Set a shortcut in keybindings.json:

"key": "ctrl+9",
"command": "ssmacro.macro", "args": {"path": "C:\\...\\regex.json"}

You can batch multiple commands together [{...},{...}] which is useful for applying a whole set of regex operations in one go.

Phil B
  • 387
  • 5
  • 15
  • thank you for the answer, that helped me very much. But can you please add an example of combining macros or batching? I need more than one text replacements in one macro – halliballi Dec 05 '18 at 13:02
  • sorry for bothering you, found the solution for batch. just add new block like you have between [] and use comma for seperating those command blocks – halliballi Dec 05 '18 at 13:13
  • I use the same extension, but the parameter `all` didn't work? If it setted to false, nothing is replaced. if it setted to true only one match is replaced (every execution). – Syrlia Dec 18 '18 at 07:16
  • It's in the documentation. `all` param tells whether the operation happens just in the current selection, or in the entire document. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Advanced_searching_with_flags for flags, which are a must to use this. Probably you are missing "g". – Phil B Dec 19 '18 at 15:51
  • No need for indirection in the JSON file: being a single-action macro it can be bound directly to the key with `ssmacro.replace`. – lapo Mar 01 '19 at 14:48
  • doesn't using ```\``` in the path string give an ```Invalid escape character in string``` error? Edit also I think [macros](https://marketplace.visualstudio.com/items?itemName=geddski.macros) plugin might be easier to use. – ANimator120 Aug 28 '21 at 02:58
  • specific regex example kind of irrelevant - but you have to escape the backslash in "\s" with another backslash, this is a json file. Anyhow, I like the fact that 'macros' source is readily available on github, and the simple syntax, but I'm not sure it checks the boxes in terms of 'regex' operations. Maybe someone could figure that part out and submit another answer though. – Phil B Aug 28 '21 at 14:59
7

As of today, it seems it's still not possible without an extension. Here are 2 other extensions than the one proposed in the accepted answer (both are also open-source):

Batch Replacer (but it doesn't work on the documents open in the editor : "you must have a folder open for editing and all files in it will be updated."*)

Replace Rules: you simply add some rules in your settings.json (open the palette with F1 or ctrl+shift+p and select Preferences: open settings (JSON)).

"replacerules.rules": {
    "Remove trailing and leading whitespace": {
        "find": "^\\s*(.*)\\s*$",
        "replace": "$1"
    },
    "Remove blank lines": {
        "find": "^\\n",
        "replace": "",
        "languages": [
            "typescript"
        ]
    }
}
MagTun
  • 5,619
  • 5
  • 63
  • 104
  • The extension in the accepted answer is licensed under MIT, which is of the least restrictive of all Open Source licenses https://www.quora.com/What-is-the-difference-between-open-source-licenses-MIT-CC0-Apache-GNU-etc – Diego Shevek Jan 20 '20 at 20:52
  • Oups, sorry, I modified my answer. – MagTun Jan 21 '20 at 10:08
  • I'd have to give these 2 plus points over ssmacro based on having source links, and both seemingly more recently maintained. – Phil B Aug 28 '21 at 15:08
1

And here is an extension I wrote that allows you to save find/replaces in a file or searches across files as a named command and/or as a keybinding: Find and Transform. Using the OP's original question, make this setting (in settings.json):

"findInCurrentFile": {                // in settings.json
  "reduceUserEntry": {
    "title": "Reduce User to ...",    // will appear in the Command Palette
    "find": "CN=([^,]+).*",
    "replace": "$1",
    "isRegex": true,
    // "restrictFind": "selections",     // default is entire document
  }
},

You could also make that for searches across files with this setting:

"runInSearchPanel": {
  "reduceUserEntry": {
    "title": "Reduce User to ...",      // will appear in the Command Palette
    "find": "CN=([^,]+).*",
    "replace": "$1",
    "isRegex": true
    
    // "filesToInclude": "${fileDirname}"
    // "onlyOpenEditors": true
    // and more options
  }
}

As a standalone keybinding:

{
  "key": "alt+r",                     // whatever keybinding you want
  "command": "findInCurrentFile",     // or runInSearchPanel
  "args": {
    "find": "CN=([^,]+).*",
    "replace": "$1",   
    "isRegex": true

The extension can also run multiple finds/replaces - just put them into an array:

"find": ["<some find term 1>", "<some find term 2>", etc.

and the same with replacements, make an array of them.

Mark
  • 143,421
  • 24
  • 428
  • 436
0

Extensions folder is : %USERPROFILE%\.vscode\extensions

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103