0

I am creating a script which finds the old ip and replace with the new ip in a given input file. I have followed some examples from internet and i wrote the following script

@echo off&setlocal  
setlocal enabledelayedexpansion  
FOR /F "tokens=2 delims=:" %%f IN ('ipconfig ^| findstr /IC:"IPv4 Address"') DO set ip=%%f  
set ip1=%ip:~1%  
echo %ip1%  
set "search=old IP"  
set "replace=New IP"  
set "textfile=sample.txt"  
set "newfile=Output.txt"  
set OUTPUTLINE=  
for /f "tokens=1,* delims=¶" %%A in ( '"findstr /n ^^ %textfile%"') do (
    SET string=%%A
    for /f "delims=: tokens=1,*" %%a in ("!string!") do set "string=%%b"
    if  "!string!" == "" (
        echo.>>%newfile%
    ) else (
        SET modified=!string:%search%=%replace%!
        echo !modified! >> %newfile%
    )
)  
del %textfile%  
rename %newfile% %textfile%  
)  
)  
endlocals

but i am not interested to create a new file and i need to modify the data in same file it self to avoid some error occurrences. could you please any one help me on this.

lit
  • 14,456
  • 10
  • 65
  • 119
IamKishore
  • 17
  • 4
  • 1
    Possible duplicate of [How can you find and replace text in a file using the Windows command-line environment?](http://stackoverflow.com/questions/60034/how-can-you-find-and-replace-text-in-a-file-using-the-windows-command-line-envir) – Mofi May 25 '16 at 06:04
  • You do the one of three ways that programs handle this. Save the file under a new name. Delete the old file. Rename the new file to the old file. –  May 25 '16 at 06:08
  • thanks for your response #Noodles. but i don't want to create a new file . My aim is to do the operation in same file, is there any why to do?? – IamKishore May 25 '16 at 07:19
  • 2
    @IamKishore in theory there is, but batch is way too weak to handle such things. Note, the smallest amount of data a disk is able to write is a sector. Any possible solution would have to override I/O-handling of the OS and mess directly with the disk - a thing you (believe me) wouldn't want to do. Or to remote-control an application, that does. Also way too costly for the very little benefit (as most txt files probably aren't bigger than one or two sectors). – Stephan May 25 '16 at 08:45
  • After properly indenting the code, it appears that there is an extraneous closing parenthesis. Also, it should be `endlocal` rather than `endlocals`. – lit May 25 '16 at 15:41
  • 1
    *My aim is to do the operation in the same file*. You can't via a batch file. – Ken White May 25 '16 at 17:10
  • Windows expects programs to save and rename. The new file will have the attributes and time stamp of the deleted file. –  May 26 '16 at 00:47

0 Answers0