Use regex to replace in batch

Viewed 242

I just want add a single quotation to all the dates in a file by batch script. 2006/04/26 20:24:26 → '2006/04/26 20:24:26' For some reason I have to use regex.

I tried using findstr in batch ,actually it doesn't work.
SET "REGEX=[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9]" I guess I should use powershell or vbs to do it. But I'm not familiar with neither powershell nor vbs,I'm a little confused by the sample codes.

Dose anyone has some clue?

2 Answers

You can't search and replace with findstr utility, it is only meant to search for some specific patterns, and its regex arsenal is quite limited.

Instead, consider a short Powershell script that uses .NET regex:

(gc your_file.txt) -replace '\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2}', "'`$&'" | sc your_file_updated.txt

See the .NET regex demo.

NOTE:

  • (gc your_file.txt) (=(Get-Content your_file.txt)) reads in your_file.txt line by line
  • -replace runs a regex-based replacement on the contents found
  • \d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2} matches {4 digits}/{2 digits}/{2 digits} {2 digits}:{2 digits}:{2 digits} patterns
  • and then '$&' replacement pattern replaces each match with itself ($&) inside single quotes
  • sc your_file_updated.txt - (=Set-Content your_file_updated.txt) saves the result into your_file_updated.txt file.

A solution using Regex in vbscript with a batch file :

@echo off
Title Replace String using Regex with vbscript
Set "InputFile=%1"
If "%~x1" NEQ ".txt" Goto :Help
Set "OutPutFile=%~dp0OutPutFile.txt"
Call :Search_Replace "%InputFile%" "%OutPutFile%"
Start "" "%OutPutFile%" & Exit
::------------------------------------------------------------------
:Search_Replace <InputFile> <OutPutFile>
(
    echo WScript.StdOut.WriteLine Search_Replace(Data^)
    echo Function Search_Replace(Data^)
    echo Dim strPattern, strReplace, strResult,oRegExp
    echo Data = "%~1" 
    echo Data = WScript.StdIn.ReadAll
    echo strPattern = "\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2}"
    echo strReplace = "'$&'"
    echo Set oRegExp = New RegExp
    echo oRegExp.Global = True 
    echo oRegExp.IgnoreCase = True 
    echo oRegExp.Pattern = strPattern
    echo strResult = oRegExp.Replace(Data,strReplace^)
    echo Search_Replace = strResult
    echo End Function
)>"%tmp%\%~n0.vbs"
cscript //nologo "%tmp%\%~n0.vbs" < "%~1" > "%~2"
If Exist "%tmp%\%~n0.vbs" Del "%tmp%\%~n0.vbs"
Exit /B
::------------------------------------------------------------------
:Help
Color 0C & Mode 85,3
echo(
echo       Usage : Drag and Drop a txt file over this script:"%~nx0"  
Timeout /T 5 /nobreak>nul & Exit
::------------------------------------------------------------------
Related