regex search replace in batch

12,112

You can benefit from findstr command. It supports regular expressions with limited syntax. Say, you have files

ignore_me.txt
rename_me01.txt
rename_me02.txt
rename_me03.txt
rename_me04.txt

A command

dir /b | findstr "rename_me[0-9][0-9]"

will output

rename_me01.txt
rename_me02.txt
rename_me03.txt
rename_me04.txt

OK, not very good example, because you can do this with good old ? wildcard. My point is that pattern for findstr is a regular expression.

Recently I had a similar problem, but I bored trying to find out how to replace regex patterns. I'm not sure if it even possible with only native Windows commands. So, for more simple, but still native solution I referred to Windows Scripting Host. My task was to find all files that have in their names a date in format dd.mm.yyyy and replace that date with current.

The script for that is:

<job>
    <script language="JavaScript">
        var d = new Date();
        // get current date for replacement
        var currDate = (d.getDate() + "." + (d.getMonth() + 1) + "." + d.getFullYear())
            // add leading zeros to date and month
            .replace(/^([0-9])\./g, '0$1.').replace(/\.([0-9])\./g, '.0$1.');
        var fso = new ActiveXObject("Scripting.FileSystemObject");  
        var files = new Enumerator(fso.getFolder(".").files);
        var count = 0;
        for (; !files.atEnd(); files.moveNext())
        {
            var file = ""+files.item(); // make it string
            if (file.match(/[0-9]{2}\.[0-9]{2}\.[0-9]{4}/)) {
                var newName = file.replace(/[0-9]{2}\.[0-9]{2}\.[0-9]{4}/, currDate);
                fso.moveFile(file, newName);
                count++;
            }
        }
        WScript.echo("Renamed "+count+" files");
    </script>
</job>

Saved it under name u.wsf and put into the folder to those files. The extension is associated with wscript so when double clicking on the file it runs in GUI mode, but can also run in command line mode:

cscript u.wsf
Share:
12,112
standatw
Author by

standatw

Updated on June 04, 2022

Comments

  • standatw
    standatw almost 2 years

    I want to do search/replace with a regex pattern in windows batch on a set of files. It will be something like:

    if the regex matches a line matches then replace it with a new line.
    

    also I need to add a variable in the regex to just replace the value. Does anyone know how to deal with the batch script? I'm not that familiar with it. Some examples maybe helpful.