Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace only one line in text file

Tags:

powershell

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.

like image 213
Neyt Avatar asked Oct 16 '25 12:10

Neyt


2 Answers

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.

like image 185
Martin Brandl Avatar answered Oct 19 '25 07:10

Martin Brandl


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
like image 29
Ansgar Wiechers Avatar answered Oct 19 '25 05:10

Ansgar Wiechers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!