0

I have a text file which I am trying to edit via a batch script. Concretely speaking, the file contains a list of parameters and I am trying to add a path (string) right after one of the parameters (string as well).

To do so I wrote the script below which is supposed to

  • Iterate through each line of the file
  • Concatenate the parameter and the path together into a new line if the line contains the parameter I am looking for.
  • Output everything (unchanged and changed lines) to a new txt file.

In my case the parameter I am looking for in my file is "image".

Unfortunately, although the main problem here is probably that I am dumb, I have been unable to figure out why it doesn't work and would very much appreciate some help.

Here is the code:

@setlocal enableextensions enabledelayedexpansion
@echo off

push %~dp0
set "path=%UserProfile%"

REM iterate through each line of given txt file
for /F "delims="%%G in (settings.txt) do (
    set line =%%G
    if not x%line:image=%==x%line% set "newline=%line%%path%

    echo !newline! >> newFile.txt
)
popd
pause
exit /b 0

For reference, I based myself on this page to write my code.

Thanks in advance

onKapu
  • 3
  • 1
  • Apply [delayed expansion](https://ss64.com/nt/delayedexpansion.html) consistently e.g. as `if not "!line:image=!"=="!line!" set "newline=!line!%path%"` – JosefZ Aug 01 '20 at 09:26
  • `set line =%%G` sets a variable named `line` + _space_… And **never** use the system-reserved variable name `path`… – aschipfl Aug 01 '20 at 14:01

1 Answers1

0

As there were several issues with your provided code, here's an example of how I'd have expected it to look:

@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion

Set "fileIn=%~dp0settings.txt"
Set "strGet=image"
Set "strAdd=%UserProfile%"
Set "fileOut=%~dp0newFile.txt"

(
    For /F Delims^=^ EOL^= %%G In (
        '""%__AppDir__%find.exe" /V /N "" 0< "%fileIn%" 2> NUL"'
    ) Do (
        Set "strLine=%%G"
        SetLocal EnableDelayedExpansion
        If /I Not "!strLine:%strGet%=!" == "!strLine!" (
            Echo=!strLine:*]=!%strAdd%
        ) Else Echo=!strLine:*]=!
        EndLocal
    )
) 1> "%fileOut%"

I'm not going to explain how this works, in order to find out, you should try to work through it command by command, making use of each of their respective help outputs. The only things you should need to modify are the four variable definitions on lines 4..7 respectively. Please note that variable expansion and substring substitution does not work with anything you want to place in %strGet%, it has limitations!

Compo
  • 36,585
  • 5
  • 27
  • 39
  • Thank you very much! This is more that what I hoped for. Obviously I needed to properly study further both the basic syntax and the functions I was trying to use. Your code provides me with both a solution and enough hints at what I needed to look at. Have great day. – onKapu Aug 02 '20 at 02:50