Powershell:替换文件中特定行上的文本

Mor*_* S. 4 powershell replace

我有一些文本文件,看起来像这样:


文本 05-09-18
文本 17-09-18
文本 17-09-18

文本 24-09-18
文本 17-10-18


在 .txt 文件的第 15 行,我尝试将 24-09-18 更改为 24-09-2018。
只改变这个,不改变其他。

  • [15] 用空文件覆盖 .txt 文件。
  • 如果 [15] 不存在,则会更改 .txt 文件中的所有日期。

这是我到目前为止一直在做的事情:

$infolder = Get-ChildItem C:\folder\*.txt -rec
foreach ($file in $infolder)
{
(Get-Content $file.PSPath) |
Foreach-Object { $_[15] -replace '-18','-2018'} |
Set-Content $file}
Run Code Online (Sandbox Code Playgroud)

Jef*_*lin 6

Get-Content如果用作赋值语句的右侧,则将文件的内容读入数组。因此,您可以执行以下操作:

 $filecontent = Get-Content -Path C:\path\to\file.txt
 $filecontent[15] = $filecontent[15] -replace '-18','-2018'
 $Set-Content -Path C:\path\to\file.txt -Value $filecontent
Run Code Online (Sandbox Code Playgroud)

您可以在 Microsoft 的Get-Content-replaceSet-Content页面上找到更详细的文档。

注意:PowerShell 数组是零源的。如果您想更改第十六行,请使用上面的代码。如果您想更改第十五行,请使用$filecontent[14]代替$filecontent[15]