Search code examples
batch-filereplacestorebatch-processing

Batch: How to store values encountered during a regular expression search & replace (repl.bat)


Using Batch, I'm looking for a way to (1) search for a regular expression pattern and (2) store variables within that pattern... so I can use those variables while doing a search and replace.

I've been using REPL.BAT, which was created by @dbenham (original REPL.BAT post and earliest StackOverflow post). Here's an example of the scenario.

I search a document for the occurence of the following code:

driver.find_element_by_id("username").send_keys("rwbyrd")
driver.find_element_by_id("password").send_keys("password")

And replace it with...

login("rwbyrd","password")

Using the following Batch code:

type %filename% | repl "\sdriver\.find_element_by_id\(\x22username\x22\)\.send_keys\(\x22rwbyrd\x22\)\s*driver\.find_element_by_id\(\x22password\x22\)\.send_keys\(\x22password\x22\)"       "login(\x22rwbyrd\x22,\x22password\x22)" MX >%filename%.new

NOTE: \x22 = Hex for double quotes

What I am looking for is a way to store the [username] 'rwbyrd' and [password] 'password' values from the code I'm searching for & use those values when doing a replace. I'd like to find a way to achieve this within the REPL.BAT command, but I will take what I can get :). Does anyone know how to achieve this? Thanks ahead of time!


Solution

  • If you haven't done this already, I strongly recommend you execute the following commands from the command prompt:

    To get help specific to REPL.BAT:

    repl /?
    

    To get help about the JScript regular expressions used by REPL.BAT (opens up MicroSoft documentation in your web browser)

    repl /?regex
    

    To get help about the replace submatch features - the "variables" you are looking for (opens up MicroSoft documentation in your web browser)

    repl /?replace
    

    I replaced the leading \s with \b (word boundry) in your search regex. I also use un-escaped parentheses to capture the username and password values so that I can use them in the replacement string. The .*? matches the content within the parentheses literals (non-greedy match). One cosmetic change was to use \q instead of \x22.

    type %filename% | repl "\bdriver\.find_element_by_id\(\qusername\q\)\.send_keys\((.*?)\)\s*driver\.find_element_by_id\(\qpassword\q\)\.send_keys\((.*?)\)" "login($1,$2)" MX >%filename%.new
    

    Update

    Based on OP's comment, and Aacini's answer, I've updated REPL.BAT to accept a J option to specify the replacement value as a JScript expression.

    The following example will convert the username to upper case:

    type %filename% | repl "\bdriver\.find_element_by_id\(\qusername\q\)\.send_keys\((.*?)\)\s*driver\.find_element_by_id\(\qpassword\q\)\.send_keys\((.*?)\)" "'login('+$[1].toUpperCase()+','+$[2]+')'" MXJ >%filename%.new
    

    See http://www.dostips.com/forum/viewtopic.php?p=37855#p37855 for details and examples.