1

i´ve Problems replacing a string in a loop

For example: I have a File called someBlabla.txt which has multiple lines with random sentences. Now i want to read the file line by line in a for loop and replace a specific char of a word by another. I want to use the shown string replace method, means %myVar:to_replace=replace%

Has someone any hints?

Here is my Script:

REM REPLACE EXAMPLE
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION

:MAIN
set file=someBlaBla.txt
set "charToReplace=a"
set "replacer=Z"
for /f "tokens=*" %%a in (%file%) do (
    set "replaced_line=%a:%charToReplace%=%replacer%%"
    echo replacedLine=!replaced_line!
)
exit /b 0

Here is my textfile:

This is a sentence with an a
this is something
there is a car
and so on and so on
some a a a
Felix Waltl
  • 129
  • 6
  • 4
    You need to ```Set "line=%%a"``` then ```echo !line:%charToReplace%=%replacer%!"```. – Compo Sep 22 '22 at 10:20
  • @Compo: Now it works, the problem was as following: when the line `set "replaced_line=%a:%charToReplace%=%replacer%%"` is executed, the parser searches for the occurance of the **first 2 % signs**, then reads the `%a:%`... and thinks its an variable and moves on which results in an error. With the `!` signs from the variable 'line' there is no failure possibility left... – Felix Waltl Sep 23 '22 at 08:15
  • Whilst that may explain how the parser worked, it's not really, the problem, Felix Waltl. The problem was that the `for` loop variable, `%%a` is not the same as an environment variable, `%replacer%`. _(You were trying to use `%%a` as `%a%`)_. One of those differences is that the former cannot be directly expanded and substringed/substituted. So my advice was to pass the content of the `for` loop variable into an environment variable, which could then be expanded and substituted as needed. – Compo Sep 23 '22 at 11:36

0 Answers0