FIND and replace all

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
livingoff
Posts: 5
Joined: 09 Apr 2013 12:02

FIND and replace all

#1 Post by livingoff » 09 Apr 2013 12:05

I have to replace some content in all files with some specific extension.

For eg: In folder toChange i may have multiple sub folder, now I want to change text isabcd to isxyz in all the files with extension html

what will be the batch for such command, I am using windows

Actually there will be multiple items that i need to replace. I have them in key value form and need to replace all of them one by one in all the files in folder
PS: sorry about asking direct solution. BUt i have no idea about batch files :(

Endoro
Posts: 244
Joined: 27 Mar 2013 01:29
Location: Bozen

Re: FIND and replace all

#2 Post by Endoro » 09 Apr 2013 12:38

You can use WinGrep for this, it has a nice GUI.

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

Re: FIND and replace all

#3 Post by abc0502 » 09 Apr 2013 15:39

we had this problem before, not same but very similar, replace text in a file with another here
it just need a small tweak to work, but first what is the separator between the key-value words, and is the seprator itself exist in any of the keys or the values ?

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

Re: FIND and replace all

#4 Post by abc0502 » 09 Apr 2013 16:43

Try This on Sample files First, I tested but test it yourself.
Take a backup copy of all your files, the batch create a .backup copy but can be overwritten if the batch run twice.


> All what you have to do is to set the first 4 variables [ lines 4 to 7 ]
> Don't put the batch file in the main folder (toChange folder).

> EXT variable is the file types you want to replace the words in, put each extension after the other with a single space as a separator.
> MainFolder is your "toChange Folder".
> KeyValueFile is the file that hold your words that will search for and replace with.
> The Separator variable is the separator between your key-value pairs.

Code: Select all

@Echo OFF

REM ===[ SETTINGS ]==================
SET "EXT=html txt csv sh"
SET "MainFolder=%userprofile%\desktop\Main"
SET "KeyValueFile=%userprofile%\desktop\Key-Value.txt"
SET "Separator=:"

Rem ===[ Main Code ]==================
Rem Get Extension one by one and Pass it to Step2
Echo.
For %%A In (%EXT%) Do (
   Echo  ^> Processing %%A Files
   CALL :Step2 "%%A"
   )
Echo.
Echo All Done.
Exit /B

Rem === [ Batch End Here and the Functions is below ]=============================================
Rem Step2
Rem Back original files and then pass the files path and name to Step3
:Step2 <File_Extension>
SET "Type=%~1"
For /F "delims=" %%a In (' DIR /B /S /A:-D "%MainFolder%\*.%Type%" ') Do (
   Copy /y "%%a" "%%a.backup" >NUL
   CALL :Step3 "%%a" "%%~nxa"
   )
GOTO :EOF

Rem Step3
Rem Take Key-Value Pairs and pass it to Replace Function
:Step3 <InFile_Path> <InFile_Name>
Rem These two will be used in the Replace Function
SET "InFile=%~1"
SET "InFileName=%~2"

Rem Get Key-Value and replace
SETLOCAL EnableDelayedExpansion
For /F "tokens=1,2 delims=%Separator%" %%A In (' Type "%KeyValueFile%" ') Do (
   SET "Replace=%%A"
   SET "ReplaceWith=%%B"
   Call :Replace "!Replace!" "!ReplaceWith!"
)
ENDLOCAL
Goto :EOF

Rem Replace Function
Rem Replace Key with Value
:Replace <Word_to_Replace> <Word_2_Replace_with>
REM Get Total Lines Number [including empty lines]
FOR /F %%A IN ('TYPE "%InFile%"^|find /v /c ""') DO SET "Till=%%A"
REM Create The OutFile with changes
SETLOCAL EnableDelayedExpansion
<"!InFile!" (
  FOR /L %%a IN (1 1 0) DO SET /p "="
  FOR /L %%A IN (1 1 %Till%) DO (
   SET "line="
   SET /P "line="
   IF "!line!x" == "x" ( Echo.
   ) ELSE (
     set "FinalLine=!line:%~1=%~2!"
     Echo !FinalLine!)
  )
)>>"%InFile%.tmp"
ENDLOCAL
REM Delete Original and Rename the InFile.tmp with the InFile original Name
Del /F /Q "%InFile%" >NUL
Ren "%InFile%.tmp" "%InFileName%"
)
Goto :EOF


After you check your files and want to remove all .backup files, set the MainFolder variable and run the code

Code: Select all

@Echo OFF
SET "MainFolder=%userprofile%\desktop\Main"
Del /F /S /Q "*.backup" >NUL
Pause
Exit

livingoff
Posts: 5
Joined: 09 Apr 2013 12:02

Re: FIND and replace all

#5 Post by livingoff » 09 Apr 2013 22:48

abc0502 wrote:Try This on Sample files First, I tested but test it yourself.
Take a backup copy of all your files, the batch create a .backup copy but can be overwritten if the batch run twice.


> All what you have to do is to set the first 4 variables [ lines 4 to 7 ]
> Don't put the batch file in the main folder (toChange folder).

> EXT variable is the file types you want to replace the words in, put each extension after the other with a single space as a separator.
> MainFolder is your "toChange Folder".
> KeyValueFile is the file that hold your words that will search for and replace with.
> The Separator variable is the separator between your key-value pairs.

Code: Select all

@Echo OFF

REM ===[ SETTINGS ]==================
SET "EXT=html txt csv sh"
SET "MainFolder=%userprofile%\desktop\Main"
SET "KeyValueFile=%userprofile%\desktop\Key-Value.txt"
SET "Separator=:"

Rem ===[ Main Code ]==================
Rem Get Extension one by one and Pass it to Step2
Echo.
For %%A In (%EXT%) Do (
   Echo  ^> Processing %%A Files
   CALL :Step2 "%%A"
   )
Echo.
Echo All Done.
Exit /B

Rem === [ Batch End Here and the Functions is below ]=============================================
Rem Step2
Rem Back original files and then pass the files path and name to Step3
:Step2 <File_Extension>
SET "Type=%~1"
For /F "delims=" %%a In (' DIR /B /S /A:-D "%MainFolder%\*.%Type%" ') Do (
   Copy /y "%%a" "%%a.backup" >NUL
   CALL :Step3 "%%a" "%%~nxa"
   )
GOTO :EOF

Rem Step3
Rem Take Key-Value Pairs and pass it to Replace Function
:Step3 <InFile_Path> <InFile_Name>
Rem These two will be used in the Replace Function
SET "InFile=%~1"
SET "InFileName=%~2"

Rem Get Key-Value and replace
SETLOCAL EnableDelayedExpansion
For /F "tokens=1,2 delims=%Separator%" %%A In (' Type "%KeyValueFile%" ') Do (
   SET "Replace=%%A"
   SET "ReplaceWith=%%B"
   Call :Replace "!Replace!" "!ReplaceWith!"
)
ENDLOCAL
Goto :EOF

Rem Replace Function
Rem Replace Key with Value
:Replace <Word_to_Replace> <Word_2_Replace_with>
REM Get Total Lines Number [including empty lines]
FOR /F %%A IN ('TYPE "%InFile%"^|find /v /c ""') DO SET "Till=%%A"
REM Create The OutFile with changes
SETLOCAL EnableDelayedExpansion
<"!InFile!" (
  FOR /L %%a IN (1 1 0) DO SET /p "="
  FOR /L %%A IN (1 1 %Till%) DO (
   SET "line="
   SET /P "line="
   IF "!line!x" == "x" ( Echo.
   ) ELSE (
     set "FinalLine=!line:%~1=%~2!"
     Echo !FinalLine!)
  )
)>>"%InFile%.tmp"
ENDLOCAL
REM Delete Original and Rename the InFile.tmp with the InFile original Name
Del /F /Q "%InFile%" >NUL
Ren "%InFile%.tmp" "%InFileName%"
)
Goto :EOF


After you check your files and want to remove all .backup files, set the MainFolder variable and run the code

Code: Select all

@Echo OFF
SET "MainFolder=%userprofile%\desktop\Main"
Del /F /S /Q "*.backup" >NUL
Pause
Exit



is this case sensitive replace?

Endoro
Posts: 244
Joined: 27 Mar 2013 01:29
Location: Bozen

Re: FIND and replace all

#6 Post by Endoro » 10 Apr 2013 03:52

As far as I can see: yes.

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

Re: FIND and replace all

#7 Post by abc0502 » 10 Apr 2013 05:54

no, it's not case sensitive, i just tested again

livingoff
Posts: 5
Joined: 09 Apr 2013 12:02

Re: FIND and replace all

#8 Post by livingoff » 10 Apr 2013 12:10

abc0502 wrote:no, it's not case sensitive, i just tested again

the code didnt worked properly :( dont know why, it did worked fine on some files but didnt worked on rest :? can u pls share the format been expected in keyvalue file?

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

Re: FIND and replace all

#9 Post by abc0502 » 10 Apr 2013 14:22

The KeyValueFile is in this format:
OldWord To Replace:NewWord To Replace With
The words can contain spaces , but it must be separated by a colon, or you can change the separator variable with the separator in your file.
Old words in the left, new words in the right.
Make sure the separator is not a part of the word is being replaced with or the word that will be replaced, it won't work.

Another thing to note, i didn't test on words that contain characters which might need to be escaped, but it supposed to do that as it was tested before on parentheses.
If your key-value file is big, post a few sample lines of it and i can change the code to take your format.

livingoff
Posts: 5
Joined: 09 Apr 2013 12:02

Re: FIND and replace all

#10 Post by livingoff » 10 Apr 2013 21:51

abc0502 wrote:The KeyValueFile is in this format:
OldWord To Replace:NewWord To Replace With
The words can contain spaces , but it must be separated by a colon, or you can change the separator variable with the separator in your file.
Old words in the left, new words in the right.
Make sure the separator is not a part of the word is being replaced with or the word that will be replaced, it won't work.

Another thing to note, i didn't test on words that contain characters which might need to be escaped, but it supposed to do that as it was tested before on parentheses.
If your key-value file is big, post a few sample lines of it and i can change the code to take your format.

I have replaced the separator to
::::==::::
such that it never lies in my files

Code: Select all

"proposalId"::::==::::string.text
"something"::::==::::textwith_Underscore
"asd asdasdpot asdjasd"::::==::::yetotesthaibeedu
"something with space"::::==::::abcd.adasdaasdasd
"swith dot and all special chars . , "::::==::::abcd.adasda


the text on left is the one i want to replace and the text on right is the value it should be replaced with(case sensitive)

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

Re: FIND and replace all

#11 Post by foxidrive » 11 Apr 2013 01:17

livingoff wrote:I have replaced the separator to
::::==::::
such that it never lies in my files

Code: Select all

"proposalId"::::==::::string.text
"something"::::==::::textwith_Underscore
"asd asdasdpot asdjasd"::::==::::yetotesthaibeedu
"something with space"::::==::::abcd.adasdaasdasd
"swith dot and all special chars . , "::::==::::abcd.adasda


the text on left is the one i want to replace and the text on right is the value it should be replaced with(case sensitive)


You can't do that. The batch code expects a single character and not a string - and some characters like % are not going to work.

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

Re: FIND and replace all

#12 Post by foxidrive » 11 Apr 2013 02:10

Here's a batch file that is pretty robust to replace text using pairs of terms, and in every file in the folder. It replaces the original files so test it well first.
Single % characters will even work.

An example command line would be like this:

SAR "blue" "red" "cat" "dog" "traffic light" "Go very fast" "Peter" Paul"


Code: Select all

:: Search and replace pairs of terms
@echo off
if "%~2"=="" (
echo Search and Replace multiple pairs of strings
echo.
echo.usage: SAR.BAT "search string1" "new string1" ... "search string4" "new string4"
echo.
echo.It will replace search string1 with new string1
echo.and then will replace search string2 with new string2, etc
echo.
echo.You can use 1 pair of terms, or up to 4 pairs of terms
echo.
echo.This batch file will process every file in the current folder.
echo.

pause
goto :EOF
)

set "tempfile=%temp%\sartmp.vbs"
echo>  "%tempfile%" s = Wscript.StdIn.ReadAll
echo>> "%tempfile%" s = Replace(s,"%~1","%~2")
echo>> "%tempfile%" s = Replace(s,"%~3","%~4")
echo>> "%tempfile%" s = Replace(s,"%~5","%~6")
echo>> "%tempfile%" s = Replace(s,"%~7","%~8")
echo>> "%tempfile%" Wscript.Echo (s)

for /f "delims=" %%a in ('dir /b /a-d /on ^|find /i /v "%~nx0"') do (
echo processing "%%a"
cscript /nologo "%tempfile%" <"%%a" > "fileout.tmp"
move /y "fileout.tmp" "%%a" >nul
)

del "%tempfile%"
echo done
pause

livingoff
Posts: 5
Joined: 09 Apr 2013 12:02

Re: FIND and replace all

#13 Post by livingoff » 11 Apr 2013 11:28

foxidrive wrote:Here's a batch file that is pretty robust to replace text using pairs of terms, and in every file in the folder. It replaces the original files so test it well first.
Single % characters will even work.

An example command line would be like this:

SAR "blue" "red" "cat" "dog" "traffic light" "Go very fast" "Peter" Paul"


Code: Select all

:: Search and replace pairs of terms
@echo off
if "%~2"=="" (
echo Search and Replace multiple pairs of strings
echo.
echo.usage: SAR.BAT "search string1" "new string1" ... "search string4" "new string4"
echo.
echo.It will replace search string1 with new string1
echo.and then will replace search string2 with new string2, etc
echo.
echo.You can use 1 pair of terms, or up to 4 pairs of terms
echo.
echo.This batch file will process every file in the current folder.
echo.

pause
goto :EOF
)

set "tempfile=%temp%\sartmp.vbs"
echo>  "%tempfile%" s = Wscript.StdIn.ReadAll
echo>> "%tempfile%" s = Replace(s,"%~1","%~2")
echo>> "%tempfile%" s = Replace(s,"%~3","%~4")
echo>> "%tempfile%" s = Replace(s,"%~5","%~6")
echo>> "%tempfile%" s = Replace(s,"%~7","%~8")
echo>> "%tempfile%" Wscript.Echo (s)

for /f "delims=" %%a in ('dir /b /a-d /on ^|find /i /v "%~nx0"') do (
echo processing "%%a"
cscript /nologo "%tempfile%" <"%%a" > "fileout.tmp"
move /y "fileout.tmp" "%%a" >nul
)

del "%tempfile%"
echo done
pause


my text will have double quotes which i want to be replaced
my text will be as follows
if (loUserAgent.toLowerCase().indexOf("firefox") > -1
|| (loUserAgent.toLowerCase().indexOf("msie") > -1 && loUserAgent.toLowerCase().indexOf("msie 7") != -1))

and i want it to be converted to
if (loUserAgent.toLowerCase().indexOf(aaa.FIRE_FOX) > -1
|| (loUserAgent.toLowerCase().indexOf(aaa.MSIE) > -1 && loUserAgent.toLowerCase().indexOf(aaa.IE_7) != -1))\

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

Re: FIND and replace all

#14 Post by abc0502 » 11 Apr 2013 12:31

if your code you want to replace and the one that will be replaced with is consisting from two lines then replace each line alone, your KeyValueFile should be like this:
if (loUserAgent.toLowerCase().indexOf("firefox") > -1:if (loUserAgent.toLowerCase().indexOf(aaa.FIRE_FOX) > -1
|| (loUserAgent.toLowerCase().indexOf("msie") > -1 && loUserAgent.toLowerCase().indexOf("msie 7") != -1)):|| (loUserAgent.toLowerCase().indexOf(aaa.MSIE) > -1 && loUserAgent.toLowerCase().indexOf(aaa.IE_7) != -1))\

a colom will be a seprator.

BTW, this is based on my code, Foxidrive code is designed to take input from the cmd window like when you pass a parameters to an application.

you can automate this using another batch file to input the string that need replace with the string that will be replaced with.

Post Reply