Page 1 of 1

Replacing Text

Posted: 24 May 2011 17:36
by Cleptography
Though it is not logical to do so these days just to be curious, is there a way to find and replace a line in a text file using batch without the need of creating an external temp file.

Replace 0x10000 with 0x10001

mov SYS_write, %g1
mov 1, %o0
set 0x10000, %o1

Re: Replacing Text

Posted: 25 May 2011 00:49
by orange_batch
Reads input file, prefixes all lines with it's line number (so as not to lose blank lines), clears input file, rewrites input file. Probably not perfect, as text processing in batch never is, but should work for things that don't include special characters.

Without enabledelayedexpansion.

Code: Select all

for /f "delims=] tokens=1*" %%x in ('type myfile.txt^|find /v /n ""^&type nul^>myfile.txt') do (
rem How to match line number:
if "%%x"=="[63" (
echo:Prefix %%y Suffix whatever.>>myfile.txt
) else if "%%x"=="[64" (
echo:Prefix %%y Suffix same deal.>>myfile.txt
) else (
rem Match text within line:
echo:%%y|(find "0x10000" >nul&&echo:Prefix %%y Suffix again.>>myfile.txt||echo:%%y>>myfile.txt)
))
rem The line after the logical OR simply rewrites the original line.

Or if you want to process the line's contents, whatever you want to do to it...

Code: Select all

) else (
rem Match text within line:
set "line=%%y"
echo:%%y|(find "0x10000" >nul&&(call set line=%%line:~2,1%%&set /a line*=2))
call echo:%%line%%>>myfile.txt
))

Alternatively...

Code: Select all

) else (
rem Match text within line:
set "line=%%y"
echo:%%y|(find "0x10000" >nul&&set flag=1)
if defined flag (
set flag=
call set line=%%line:~2,1%%
set /a line*=2
set /a foundlines+=1
rem Whatever you want.
)
call echo:%%line%%>>myfile.txt
))

Re: Replacing Text

Posted: 25 May 2011 16:45
by Cleptography
Thank you for the response orange_batch. Yet another method I might try would be...

Code: Select all

@echo off
 setlocal enabledelayedexpansion

set strR=%~1
set strW=%~2
set file=%~3

for /f "tokens=*" %%- in (%file%) do (
   set str=%%-&&call :NEXT
)
goto :eof

:NEXT
set str=!str:%strR%=%strW%!
echo.%str%
goto :eof

...just excepts command args with string to find and replace, problem would be only if two exact strings occur and how to only change one occurrence instead of all of them.

Re: Replacing Text

Posted: 26 May 2011 06:35
by orange_batch
Yes, you can't using substring replace. And still there's the issue of losing blank lines.

As an update to my previous message, flags can be useful for certain things but the example I provided as-is is kind of silly. Might as well:

Code: Select all

) else (
rem Match text within line:
set "line=%%y"
echo:%%y|(find "0x10000" >nul&&(
call set line=%%line:~2,1%%
set /a line*=2
set /a foundlines+=1
rem Whatever you want.
))
call echo:%%line%%>>myfile.txt
))