简体   繁体   中英

A Batch file to read a file and replace a string with a new one

I want to create a batch file to read every line of a file in a loop and replace a string with another one. Following is my code snippet:

for /F "tokens=*" %%i in (myfile) do (
  set str=%%i
  set str=%str: %oldstring% = %newstring%%
echo %str% >> newfile
)

This results in a newfile with 'Echo is off' as many lines as there are in myfile. Seems like str variable holds no value at all when assigned to %%i. Can someone help me?

Try out this small script:

@echo off
set val=50
echo %val%
for /l %%i in (1,1,1) do (
    set val=%%i
    echo %val%
)
echo %val%
pause>nul

The output is:

50
50
1

Not what you expected, right?

That's because in a for loop, variables aren't updated until the loop has finished. To combat this, you can use setlocal enabledelayedexpansion , and replace the percent signs ( % ) with an exclamation mark ( ! ):

@echo off
setlocal enabledelayedexpansion
set val=50
echo %val%
for /l %%i in (1,1,1,) do (
    set val=%%i
    echo !val!
)
echo %val%
pause>nul

The output:

50
1
1

The reason the str variable holds no value (during the for loop) is because it hasn't been set beforehand.

So, with these quick modifications, your script will work...

setlocal enabledelayedexpansion
for /f "tokens=*" %%i in (myfile) do (
    set str=%%i
    set str=!str: %oldstring% = %newstring%!
    echo !str! >> newfile
)

By the way, this snippet is assuming that oldstring and newstring won't be set within the forloop, otherwise things will get messy.

Have fun.

having spent some time at this I got the correct way:

@echo off
setlocal enabledelayedexpansion

set oldstring=AF-07295
set /a count=1000

for %%f in (*.*) do (
  set /a count=!count!+1
  for /f "tokens=*" %%i in (%%f) do (
    set str=%%i

    call set str=%%str:!oldstring!=!count!%%
    echo !str! >> %%~nf.ordnew

  )
)

endlocal
setlocal ENABLEDELAYEDEXPANSION
set filein="c:\program files\test1.txt"
set fileout="c:\program files\test2.txt"
set old=@VERSION@
set new=2.0.3
for /f "tokens=* delims=¶" %%i in ( '"type %filein%"') do (
    set str=%%i
    set str=!str:%old%=%new%!
    echo !str! >> %fileout% 
)

working perfect and isn't removing white spaces at the begining of the lines file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM