使用powershell替换文件的指定行号处的文本

Jan*_*nki 6 powershell

如果有一个文件例如test.config,则该文件在第140行和第170行之间包含工作"WARN",还有其他行,其中有"WARN"字,但我想用第140行和第170行替换"WARN"单词"DEBUG",并保持文件的剩余文本相同,并且在保存时,"WARN"仅在第140和170行之间被"DEBUG"替换.剩下的所有文字都不受影响.

ste*_*tej 7

看看$_.ReadCount哪个会有所帮助.仅作为示例,我仅替换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
Run Code Online (Sandbox Code Playgroud)

之后,该文件将包含:

1
2
3
4
5
6
7
8
9
replaced
replaced
replaced
replaced
replaced
replaced
16
17
18
19
20
Run Code Online (Sandbox Code Playgroud)


rer*_*run 0

这是测试文件

text
text
DEBUG

DEBUG


TEXT
Run Code Online (Sandbox Code Playgroud)

--

PS:\ gc .\stuff1.txt |% { [system.text.regularexpressions.regex]::replace($_,"WARN","DEBUG") }  > out.txt
Run Code Online (Sandbox Code Playgroud)

Out.txt 看起来像这样

文本 文本 调试

调试

文本