Search code examples
batch-filereplacenotepad

Replace characters, (alternative to SED), using a batch file


I want to replace all , in a text File with . via Batch.

Actually I just need an alternative for this command

sed.exe "s/,/./g" $clearances.txt$ > $clearance_out.txt$

Problem is sed.exe is not installed on every PC I want to use this on so I plan to read and replace with the standard notepad editor from Windows.

Does anyone know how?

Example for the clearances.txt:

-12,7
-5,6
-7,6
-3,9

Solution

  • You could do it the following way (using a batch file equivalent for your sed):

    Name the file replace_string.bat

    @echo off 
        setlocal enableextensions disabledelayedexpansion
    
        set "search=,"
        set "replace=."
    
        set "textFile=clearances.txt"
    
        for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
            set "line=%%i"
            setlocal enabledelayedexpansion
            >>"%textFile%" echo(!line:%search%=%replace%!
            endlocal
        )
    

    First we want to make sure the delayed expansion is disabled (for the for magic to work). Next set the variables to search for and in file.

    Then in loop I use type to display contents of the file. Then ^ is used to escape & (run first command and then second) and > (redirect).

    Then save the loop variable %%i (the double %% is there due to the fact that we are in batch file) into line variable so we could use it. Then we need to enable delayedexpansion so we could use the !...!.

    The tricky part is echo(!line:%search%=%replace%!.

    echo( normally prints empty line. Here you need to have it for line variable expansion. Without it you would get something like:

    'line:' is not recognized as an internal or external command

    So we where we have then (thanks to expansion) 12,7:,=. which results into the final result 12.7