用PowerShell替换文本文档中的多行文本



我有两个不同短语的多行文本文件。我想按顺序改变这些短语中的每一个(<<不是多余的)。这就是说,例如,取一个具有以下内容的文本文件:

Test  <>
some seemingly random stuff
Results <>
more seemingly random stuff
Test  <>
Gibberish
Results <>
more gibberish
Test  <>
lines of stuff here too
Results <>
more lines of stuff here as well
Test  <>
a few more pages of garble
Results <>
Even more garble at the end of what I am concerned with.

我想对这样一个文件做的是在<>,但它将包含一个顺序的数字指示符。我想把它改成这样:

Test <This is for test 1:>
some seemingly random stuff
Results <Values for test 1:>
more seemingly random stuff
Test <This is for test 2:>
Gibberish
Results <Values for test 2:>
more gibberish
Test <This is for test 3:>
lines of stuff here too
Results <Values for test 3:>
more lines of stuff here as well
Test <This is for test 4:>
a few more pages of garble
Results <Values for test 4:>
Even more garble at the end of what I am concerned with.

我试过的是:

Get-Content -Path C:test-directoryTest-Text.txt | Foreach-Object {
$_ -replace "Test <>", "Test <This is for test >" `
-replace "Results <>", "Results <Values for test >"
} | Set-Content c:test-directoryNew-Test-Text.txt

现在…这个工作得很好……差不多。我需要实现的是;我只是不明白,是怎么告诉它把1放在第一行之后,1在第二行之后,2在第三行之后,2在第四行之后,3在第五行之后……等。我正在考虑尝试使用:

$_ -replace "Test <>", "Test <This is for Test $N" `
-replace "Results <>", "Results <Values for test $N>"

并有一些方法强制$N在每次输出时增加($N = $N+1)…但我不知道该怎么做。如有任何意见,不胜感激。

您可以使用switch:

轻松地做到这一点
$n = 1  # set the starting number
$newContent = switch -Regex -File 'C:test-directoryTest-Text.txt' {
'^s*Tests+<>'    { 'Test <This is for test {0}:>'-f $n }
'^s*Resultss+<>' { 'Results <Values for test {0}:>'-f $n++ }
default         { $_ }  # return this line unchanged
}
$newContent | Set-Content 'C:test-directoryNew-Test-Text.txt'

对于非常大的文件,您可以选择在交换机中写入输出,因此它不会首先在变量中收集所有内容,然后写入磁盘。
当然,这将使整个工作变慢,因为更多的磁盘写操作。

$n       = 1                                        # set the starting number
$outFile = 'C:test-directoryNew-Test-Text.txt'
'' | Set-Content -Path $outFile                     # create or empty the resulting file
switch -Regex -File 'C:test-directoryTest-Text.txt' {
'^s*Tests+<>'    { Add-Content -Path $outFile -Value ('Test <This is for test {0}:>'-f $n) }
'^s*Resultss+<>' { Add-Content -Path $outFile -Value ('Results <Values for test {0}:>'-f $n++) }
default         { Add-Content -Path $outFile -Value $_ }  # write this line unchanged
}

输出:

Test <This is for test 1:>
some seemingly random stuff
Results <Values for test 1:>
more seemingly random stuff
Test <This is for test 2:>
Gibberish
Results <Values for test 2:>
more gibberish
Test <This is for test 3:>
lines of stuff here too
Results <Values for test 3:>
more lines of stuff here as well
Test <This is for test 4:>
a few more pages of garble
Results <Values for test 4:>
Even more garble at the end of what I am concerned with.

相关内容

最新更新