Search and replace text in file

1. VBScript

‘Usage: cscript SR.vbs readme.txt  Robert Julias

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
objFile.Close

 

2. PowersHELL (Ex 1)

cat readme.txt | %{$_ -replace “oldtext”,”newtext”}

 

3. PowersHELL (Ex 2)

Get-ChildItem -exclude *.bak | Where-Object {$_.Attributes -ne “Directory”} |
ForEach-Object { Copy-Item $_ “$($_).bak”; (Get-Content $_) -replace
“oldtext”,”newtext” | Set-Content -path $_ }

 

4. PowersHELL (Ex 3)

param( [string]$Find, [string]$Replace, [string]$Path )
gci -Path $Path -recurse | foreach{ (gc $_) -replace $Find,$Replace | sc $_ }

./sr.ps1 oldtext newtext *.txt

 

5. PowersHELL (Ex 4)

(Get-Content C:\Scripts\readme.txt) |
Foreach-Object {$_ -replace “\*”, “@”} |
Set-Content C:\Scripts\readme_new.txt

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: