How to find and replace text in large file
August 3, 2011 at 4:36 pm 1 comment
Hey folks,
Back after a looooong break.
This time I would like to replace text in a file. Hmm…
You might wonder that it’s so simple, Open file press ctrl + F and replace from there. But here the file is very big in size. It’s 300 MB File.
I’ve tried different editor to replace it but I’m failed and hopeless. I thought I need to replace it one by one.
Then one of my friend told me to try command line argument through cmd and I have surfed for that and I found below article.
http://blogs.technet.com/b/heyscriptingguy/archive/2005/02/08/how-can-i-find-and-replace-text-in-a-text-file.aspx
Here you need to create one VB Script (.vbs) file and put these text inside it. let’s say the name of the file is 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.WriteLine strNewText
objFile.Close
After creating file you need to fire below command from command prompt.
cscript replace.vbs “C:\Scripts\Text.txt” “test ” “temp “
Remember, you need to fire this command from the same drive/directory where your replace.vbs is.
But In my case this trick doesn’t work because I need to replace double quote (“) into single quote(‘) and I have tried different solution but it didn’t work.
Finally I thought to change the replace.vbs file. and I have do below change in file.
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, """", "'")
Set objFile = objFSO.OpenTextFile(strFileName, ForWriting)
objFile.WriteLine strNewText
objFile.Close
and then I’ve run below command.
cscript replace.vbs "C:\Scripts\Text.txt"
its done the trick in just 3 sec. Hurray
…
Entry filed under: Uncategorized. Tags: find and replace in txt file, Replace in txt file.
1.
Samir Varteji | August 3, 2011 at 5:10 pm
Very very useful tip.
It reminds me of old days when we were using vb 6.
Keep writing dear..