Batch executable to find replace text?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Message
Author
jeff p
Posts: 42
Joined: 28 Jul 2009 10:21

Batch executable to find replace text?

#1 Post by jeff p » 07 Oct 2012 01:45

Hello.

I have a large text document, (notepad) which contains about 50 names throughout.. ie Jim, Fred, Mary, etc. Is it possible to create a batch file which will search through the document, find and replace multiple names. I know I can do this one at a time.. but this is a process I need to repeat many times.

ie something like

in the document located on D:/Address_list/Names.txt

find "Bob Jones" replace with "Fred Thomas"
find "Mary" replace with "Jane"
find "Tom Riley" replace with "Doug Smith"

etc..

is something like this possible?

thanks for any help

Jeff

abc0502
Posts: 1007
Joined: 26 Oct 2011 22:38
Location: Egypt

Re: Batch executable to find replace text?

#2 Post by abc0502 » 07 Oct 2012 03:47

Note:

Code: Select all

('findstr /n /r /v /c:"[^    ]" "%file%"')

between the [^ and ], it is one space and one tab character.

For NOW THIS BATCH IS NOT WORKING
Try this,
First:
> make a text file that contain old names and new names, and put them in this format old:new
Bob Jones:Fred Thomas
Mary:Jane
Tom Riley:Doug Smith

Then set the variables in the top of the batch,
>source: is the file where you want to replace names.
>list: is the file that contain old and new names.

The batch will first take a back-up copy of the original file and then start search and replace.

Code: Select all

@Echo Off & Cls & Color 0E & Mode 55, 10

:: set variables
set "source=1.txt"
set "list=replace.txt"

:: Back-up Original FIle
Copy "%source%" "%source%.bak" >nul
:: source location
For /f "tokens=* delims=" %%A in ('dir /b "%file%"') Do set "loc=%%~dpA"
:: source total line number
For /f "skip=2 tokens=1 delims=[]" %%A in ('find /N /V "" "%source%"') Do set "Lline=%%A"
:: search and replace
For /F "tokens=1,* delims=:" %%a in ('Type "%list%"') Do (
   Call :Find_Replace "%source%" "%%a" "%%b"
   ping localhost -n 1 >nul
   del /f /q "%source%" >nul
   ping localhost -n 1 >nul
   ren "temp.txt" "%source%"
   ping localhost -n 1 >nul
)

Echo.&Echo.&Echo.&Echo.&Echo          Done!
pause >nul
Exit /B

:: Find and Replace Function
:Find_Replace [ Call :Find_Replace "source_file" "old_word" "new_word" ]
set "file=%~1"
set "W1=%~2"
set "W2=%~3"

Setlocal EnableDelayedExpansion
<"%file%" (
   for /l %%i in (1 1 0) do set /p "="
:: space between [^ and ] is one space and one TAB character
   for /f "tokens=1,2 delims=:" %%A in ('findstr /n /r /v /c:"[^    ]" "%file%"') Do (
      for /l %%i in (1 1 %Lline%) do (
         set "ln="
         set /p "ln="
         If "%%A:!ln!" EQU "%%A:%%B" ( echo(!ln!
            ) else ( echo(!ln:%W1%=%W2%! )
      )
   )
)>>"%loc%\temp.txt"
endlocal
goto :eof

This line

Code: Select all

ping localhost -n 1 >nul
to give time between deleting and renaming to prevent errors
Last edited by abc0502 on 11 Oct 2012 18:53, edited 2 times in total.

jeff p
Posts: 42
Joined: 28 Jul 2009 10:21

Re: Batch executable to find replace text?

#3 Post by jeff p » 07 Oct 2012 05:02

Thanks for the code abc0502!

I really appreciate this!

It's exactly what I would be looking for, but cant seem to get it to work.
Ive tried adding this numerous ways..
..should have mentioned I was a complete noob.


I've called my document: FindReplaceNamesDocument.txt
and my list: FindReplaceNamesList.txt


Here's how I'm adding it in the code (incorrectly, no doubt)

any ideas?

thanks again

Code: Select all


@Echo Off & Cls & Color 0E & Mode 55, 10

:: set variables

set "source=FindReplaceNamesDocument.txt"
set "list=FindReplaceNamesList"

:: Back-up Original FIle
Copy "%source%" "%source%.bak" >nul

:: Search and Replace
For /f "skip=2 tokens=1 delims=[]" %%A in ('find /N /V "" "%source%"') Do set "Lline=%%A"
For /F "tokens=1,* delims=:" %%a in ('Type "%list%"') Do (
   Call :Find_Replace "%source%" "%%a" "%%b"
   ping localhost -n 1 >nul
   del /f /q "%source%" >nul
   ping localhost -n 1 >nul
   ren "temp.txt" "%source%"
   ping localhost -n 1 >nul
)

Echo.&Echo.&Echo.&Echo.&Echo          Done!
pause >nul
Exit /B

:: Find and Replace Function
:Find_Replace [ Call :Find_Replace "source_file" "old_word" "new_word" ]
set "file=%~1"
set "W1=%~2"
set "W2=%~3"

Setlocal EnableDelayedExpansion
<"%file%" (
   for /l %%i in (1 1 0) do set /p "="
   for /f "tokens=1,2 delims=:" %%A in ('findstr /n /r /v /c:"[^    ]" "%file%"') Do (
      for /l %%i in (1 1 %Lline%) do (
         set "ln="
         set /p "ln="
         If "%%A:!ln!" EQU "%%A:%%B" ( echo(!ln!
            ) else ( echo(!ln:%W1%=%W2%! )
      )
   )
)>>temp.txt
endlocal
goto :eof

Last edited by jeff p on 07 Oct 2012 06:08, edited 1 time in total.

abc0502
Posts: 1007
Joined: 26 Oct 2011 22:38
Location: Egypt

Re: Batch executable to find replace text?

#4 Post by abc0502 » 07 Oct 2012 05:10

are the txt files in the same location with the batch, all 3 in one dir.
if not you will have to put the full location to the documents
like this for example, on in c:\files, and the other in the C:\ dir.

you forgot ".txt" at the end in the list variable

Code: Select all

set "source=C:\files\FindReplaceNamesDocument.txt"
set "list=C:\FindReplaceNamesList"


i changed the code above so it will output the temp file in the same location where the sourec exist.

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Batch executable to find replace text?

#5 Post by foxidrive » 07 Oct 2012 05:55

The 'list' filename also needs a .txt extension, right?

jeff p
Posts: 42
Joined: 28 Jul 2009 10:21

Re: Batch executable to find replace text?

#6 Post by jeff p » 07 Oct 2012 06:06

Thanks abc0502, and Foxidrive

yeah, It was the missing .txt

Thanks for pointing that out.

I guess I would make a terrible programer.. lol

either way.. works great!

Thanks allot!

Jeff

jeff p
Posts: 42
Joined: 28 Jul 2009 10:21

Re: Batch executable to find replace text?

#7 Post by jeff p » 07 Oct 2012 08:48

Sorry to bother...

The code worked great initially, but after copying it once again, it no longer works.
I re-pasted it from this website.

When I run the bat file:

It replaces the first name in the list only, and the cmd prompt window hangs, where it originally indicated "Done"

My source text document is only 4 sentences in length.
and my list contains only 4 pairs of names.

any ideas as to whats happening?

thanks for any help.

Jeff

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Batch executable to find replace text?

#8 Post by foxidrive » 07 Oct 2012 08:57

If the source document does not have a trailing CR/LF then findstr will hang in some cases.

A solution is to add an enter on the end of the last line, or use GNU SED for Windows in a simpler batch file as it is designed to handle text rearrangement.

jeff p
Posts: 42
Joined: 28 Jul 2009 10:21

Re: Batch executable to find replace text?

#9 Post by jeff p » 07 Oct 2012 09:08

foxidrive wrote:A solution is to add an enter on the end of the last line, or use GNU SED for Windows in a simpler batch file as it is designed to handle text rearrangement.


Thanks Foxidrive,

I'm not sure what that means.

add GNU SED at the end of the code or in the source?

abc0502
Posts: 1007
Joined: 26 Oct 2011 22:38
Location: Egypt

Re: Batch executable to find replace text?

#10 Post by abc0502 » 07 Oct 2012 09:44

no, sed is an extrenal exe program used to process files, like search and replace.

go to the source file and open it, then in the last line point with your mouse at the end of it then press enter to add extra empty line then save it and run the batch to replace

jeff p
Posts: 42
Joined: 28 Jul 2009 10:21

Re: Batch executable to find replace text?

#11 Post by jeff p » 07 Oct 2012 10:21

I'll try that

Thanks!

Jeff

mid_life_crisis
Posts: 22
Joined: 26 May 2011 07:56

Re: Batch executable to find replace text?

#12 Post by mid_life_crisis » 11 Oct 2012 11:21

Hello. I have a question on the code supplied here. This is exactly what I was looking for (search is your friend 8) ) but I cannot make it work. I created the reference file with the names (in my case one value is a number and the other a name). The file I need to alter is a csv file (no problem changing it to a text file if necessary, which is what I have done) with three fields. The first field is of no consequence and can actually be lost with no ill effects. The second field is the one I need changed. It currently has a number and I need it to have the name from the reference file. The third field is a date, with slashes.

I've been trying to figure out exactly how the supplied code works so I can make modifications as necessary but I can't begin to figure out exactly what is going on. If I run the file as supplied, it appears to run properly, but the output file is empty.

Suggestions?

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Batch executable to find replace text?

#13 Post by foxidrive » 11 Oct 2012 16:24

I couldn't get abc0502's code to work either. It created a zero byte file.

You can use this: call it sar.bat

Code: Select all

:: Search and replace - sar.bat
@echo off
if "%~2"=="" (
echo search and replace usage: "%~nx0" "search string" "new string"
echo.
echo. input file is in.txt and output file is out.txt
pause
goto :EOF
)


set "file=in.txt"
set "newfile=out.txt"
set "oldstr=%~1"
set "newstr=%~2"

set "tempfile=%temp%\sartmp.vbs"
echo> "%tempfile%" s = Wscript.StdIn.ReadAll
echo>> "%tempfile%" Wscript.Echo Replace(s,"%oldstr%","%newstr%")

type "%file%" |cscript /nologo "%tempfile%"  > "%newfile%"
del "%tempfile%"



and another batch file to help use it:

This uses an input file called "file.csv" and creates "file2.csv"

Code: Select all

@echo off
copy /b /y "file.csv" "in.txt" >nul

call :replace "Bob Jones" "Fred Thomas"
call :replace "Mary" "Jane"
call :replace "Tom Riley" "Doug Smith"

move /y "in.txt" "file2.csv" >nul
goto :eof

:replace
call sar.bat "%~1" "%~2"
move /y "out.txt" "in.txt" >nul



This is the input test file
1,2,3Bob Jones
2,3,4Mary
4,5,6Tom Riley


This is the result.
1,2,3Fred Thomas
2,3,4Jane
3,4,5Doug Smith

abc0502
Posts: 1007
Joined: 26 Oct 2011 22:38
Location: Egypt

Re: Batch executable to find replace text?

#14 Post by abc0502 » 11 Oct 2012 18:48

Sorry for that, i tested again, it do the job but it generate to many empty lines after it finish.

But did any one changed the spaces here:

Code: Select all

('findstr /n /r /v /c:"[^    ]" "%file%"')

between the [^ and ], it is one space and one tab character.

it's my mistake i didn't point to that when wrote the code sorry :oops:
and as i said now it generate too many empty lines at the end of the new replaced file, and i have no idea why that is happening now ? :? :roll:
it was working fine when i was testing it first time

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Batch executable to find replace text?

#15 Post by foxidrive » 11 Oct 2012 19:02

I still can't get it to work with a spaceTAB or TABspace - it creates a zero byte 1.txt file.


1.txt

1,2,3Bob Jones
2,3,4Mary
3,4,5Tom Riley


replace.txt

Bob Jones:Fred Thomas
Mary:Jane
Tom Riley:Doug Smith

Post Reply