Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing a text at specified line number of a file using powershell

Tags:

powershell

IF there is one file for example test.config , this file contain work "WARN" between line 140 and 170 , there are other lines where "WARN" word is there , but I want to replace "WARN" between line 140 and 170 with word "DEBUG", and keep the remaining text of the file same and when saved the "WARN" is replaced by "DEBUG" between only lines 140 and 170 . remaining all text is unaffected.

like image 555
Janki Avatar asked May 18 '11 06:05

Janki


1 Answers

Look at $_.ReadCount which will help. Just as a example I replace only rows 10-15.

$content = Get-Content c:\test.txt
$content | 
  ForEach-Object { 
    if ($_.ReadCount -ge 10 -and $_.ReadCount -le 15) { 
      $_ -replace '\w+','replaced' 
    } else { 
      $_ 
    } 
  } | 
  Set-Content c:\test.txt

After that, the file will contain:

1
2
3
4
5
6
7
8
9
replaced
replaced
replaced
replaced
replaced
replaced
16
17
18
19
20
like image 182
stej Avatar answered Nov 15 '22 07:11

stej