Reputation: 490
Here is the text file I want to modify:
Sometext 2016 Sometext Sometext 6 Sometext
The two values I want to modify are on line 2 and 5 (Index 1 and 4), which are the current year and the current month.
So I did this PowerShell script:
$file = "$PSScriptRoot\myFile.txt"
$date = Get-Date
$year = $date.Year
$month = $date.Month
$oldYear = Get-Content $file | Select -Index 1
$oldMonth = Get-Content $file | Select -Index 4
(Get-Content $file).Replace($oldYear, $year) | Set-Content $file
(Get-Content $file).Replace($oldMonth, $month) | Set-Content $file
But obviously, this line
(Get-Content $file).Replace($oldMonth, $month) | Set-Content $file
will replace all the "6" in my file with the current month (which is 7 at the time I'm writing these lines), but I only want the 5th line to be replaced, not the 2nd.
Upvotes: 4
Views: 9116
Reputation: 200533
If the two lines in question are the only lines containing numbers you could use a switch
statement with regular expressions:
$file = "$PSScriptRoot\myFile.txt"
(Get-Content $file) | ForEach-Object {
switch -regex ($_) {
'^\d$' { (Get-Date).Month }
'^\d{4}$' { (Get-Date).Year }
default { $_ }
}
} | Set-Content $file
Upvotes: 2
Reputation: 59031
You don't need replace old value with new value, you can instead select the appropriate line by index and just replace the values:
$content = Get-Content $file
$content[1] = (Get-Date).Year
$content[4] = (Get-Date).Month
$content | Set-Content $file
Be aware that the Set-Content
cmdlet may change the file encoding.
Upvotes: 7