0

I need to do multiple find and replace operation on a single file. The setup is as follows:

Text data - File.txt Replacement data - File2.txt

The structure of File2.txt is like this:

ABC,XYZ
MNB,OPI
GHI,TRY

The first column is my original name (eg. ABC) and replaced with the 2nd name (eg. XYZ). This has to be done in the original File.txt

I can write a code to do a single change or to increment the name from ABC to ABC_Date but I am confused about how to loop and read both to and from names.

Any help is appreciated.

I was able to solve this by gluing together answers from: How can you find and replace text in a file using the Windows command-line environment?

How do you loop through each line in a text file using a windows batch file?

The code is:

for /F "tokens=1,2,3" %%i in (myfile.txt) do call :process %%i %%j %%k
goto thenextstep
:process
@echo %1
@echo %2
cscript replace.vbs "C:\newfile.txt" "%1" "%2"
goto :EOF

replace.vbs

Const ForReading = 1    
Const ForWriting = 2

strFileName = Wscript.Arguments(0)
strOldText = Wscript.Arguments(1)
strNewText = Wscript.Arguments(2)

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFileName, ForReading)
strText = objFile.ReadAll
objFile.Close

strNewText = Replace(strText, strOldText, strNewText)
Set objFile = objFSO.OpenTextFile(strFileName, ForWriting)
objFile.Write strNewText  'WriteLine adds extra CR/LF
objFile.Close
D.J.
  • 2,542
  • 1
  • 10
  • 15
Nona Shah
  • 59
  • 1
  • 10

1 Answers1

0

Here, This is the sample powershell code to replace multiple words from another file. You have to change the $file1Text value and $file2Text value

$file1Text = "this is sample text. You have to get the text from file" ; # your file1 data
$file2Text = "this,here it","text,data","file,physical file" # your file2 lines

$finalText = $file1Text ; # Temp variable [ optional ] : you can use file1Text directly

foreach ($str in $file2Text)
{
    $split = $str.Split(',')
    $find =  $split[0]
    $replace =  $split[1]

    $finalText = $finalText.Replace($find,$replace)    
}

cls

"Original Text :  " + $file1Text
"Replaced Text : " + $finalText
Nirav Mistry
  • 719
  • 4
  • 11