Search code examples
batch-fileregistry

Remove or replace strings from batch output


I'm querying a registry key to get a value using the command (example):

REG QUERY HKLM\Software\Foo /v Bar >>c:\Foo.txt

When opening the Foo.txt file, I get:

HKEY_LOCAL_MACHINE\Software\Foo
    Bar   REG_SZ    foo-bar

How can I remove or replace both the key-name (HKEY_LOCAL_MACHINE\Software\Foo) and the "REG_SZ"? (preferably using only batch)


Solution

  • @echo off
        setlocal enableextensions disabledelayedexpansion
    
        for /f "delims=" %%a in ('
            reg query "HKEY_LOCAL_MACHINE\SOFTWARE\RegisteredApplications" /v "Paint" 2^>nul
            ^|find "REG_SZ"
        ') do set "data=%%a"
        >foo.txt echo(%data:REG_SZ=%
    

    Execute the command, retrieve only the line containing REG_SZ and store this line into a variable. Then remove the unneeded data and save to the target file

    edited to adapt to comments

    @echo off
        setlocal enableextensions disabledelayedexpansion
    
        set "data="
        for %%k in (
            "NoPaint" "Paint"
        ) do if not defined data for /f "delims=" %%a in ('
            reg query "HKEY_LOCAL_MACHINE\SOFTWARE\RegisteredApplications" /v "%%~k" 2^>nul 
            ^|find "REG_SZ"
        ') do set "data=%%a"
    
        if defined data (
            >foo.txt echo(%data:REG_SZ=%
        ) else (
            echo ERROR 
        )
    

    Instead of directly give the key, iterate over a list of candidates until the variable that will hold the data is defined. At the end, if the variable holds data, adapt and echo, else show error