Visual Studio Code: How to automate a simple regex-find and replace?
Asked Answered
D

3

23

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
Daiseydaisi answered 3/4, 2018 at 13:59 Comment(2)
Please provide an example input and the expected output.Rainbow
Edited my answer and added an "example"Daiseydaisi
A
20

This extension does the job: ssmacro

It seems like the regex adheres to JavaScript 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.

Abatement answered 2/8, 2018 at 16:41 Comment(7)
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 macroStereography
sorry for bothering you, found the solution for batch. just add new block like you have between [] and use comma for seperating those command blocksStereography
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).Vassallo
It's in the documentation. all param tells whether the operation happens just in the current selection, or in the entire document. See developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/… for flags, which are a must to use this. Probably you are missing "g".Abatement
No need for indirection in the JSON file: being a single-action macro it can be bound directly to the key with ssmacro.replace.Lorolla
doesn't using \ in the path string give an Invalid escape character in string error? Edit also I think macros plugin might be easier to use.Handpick
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.Abatement
S
10

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"
            ]
        }
    }
    
Scrod answered 6/9, 2019 at 14:51 Comment(1)
I'd have to give these 2 plus points over ssmacro based on having source links, and both seemingly more recently maintained.Abatement
L
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.

Loudish answered 22/2, 2022 at 21:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.