Powershell Find and Replace a string in the file

Posted: October 22, 2015 in PowerShell

Search for a string and replace value after equals sign

Lets say i have a file ABC.prm with the below contents
$$V_INSERT_CNT=0
$$V_NOCHANGE_CNT=0
$$V_SOURCE_CNT=0
$$V_UPDATE_CNT=0
$$Threshold=100
$$MAX_POST_DT=20140404

I have to update the $$MAX_POST_DT value with a new value present in another file say DATE_FILE.TXT with the below data
20150416

Below is the script to achieve the above requirement.
 $filepath=$args[0]        # Pass the Actual file in our case its ABC.prm
 $DateFile=$args[1]        # pass the date file in this case it is DATE_FILE.TXT
$filepath_BKP = $filepath.split('.')[0] + "_BKP.prm"
 $orig_param=Get-Content($filepath)
 $eff_dt=Get-Content($DateFile)
foreach($L in $orig_param)
 {
 if($L -match 'MAX_RI_POST_DT=*')
 {
 $L -replace '(\d{1,8})',$eff_dt | Out-File -append -NoClobber $filepath_BKP
 }
 else
 {
 $L | Out-File -append -NoClobber $filepath_BKP
 }
 }#Remove the actual file and rename the BKP file below
If(Test-Path "$filepath")
 { # remove the file below.
 Remove-Item "$filepath"
 Write-host "The input file is deleted."
# Rename the file below
 Rename-Item -Path $filepath_BKP -NewName $filepath
 Write-host "The output body file is renamed as the input file name."
 }
Advertisements

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