【问题标题】:Powershell: Replace text on specific line in filePowershell:替换文件中特定行的文本
【发布时间】:2019-03-02 13:10:38
【问题描述】:

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


文本 05-09-18
文本 2018 年 9 月 17 日
文本 18 年 9 月 17 日

文本 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}

【问题讨论】:

标签: powershell replace


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢 Jeff 但这仅适用于特定文件,对吧?是否可以修改为对文件夹中的所有文件执行相同的操作,命名为 text1.txt、text2.txt 等...
  • 您可以将上面的代码包装在ForEach ($file in (Get-ChildItem -Path ...)) {...}中,并将上面代码中的显式路径替换为$file
【解决方案2】:

感谢您的帮助 这对我有用,它会处理 C:\folder\ 中的文件
在每个文件的第 14 行,它将 -18 替换为 -2018。
保存原始文件中的所有更改。

ForEach ($file in (Get-ChildItem -Path C:\Folder\))
{
$filecontent = Get-Content -path $file 
$filecontent[14] = $filecontent[14] -replace '-18','-2018' 
Set-Content $file.PSpath -Value $filecontent 
}

【讨论】:

    【解决方案3】:

    对“Morten S”做了一些增强。回答

    在这里,您可以通过将数组索引放在-replace 的第一个参数中来替换所有行 像这样

    $filecontent = Get-Content -Path C:\path\to\file.txt
    $filecontent[15] = $filecontent[15] -replace $filecontent[15],'some text'
    Set-Content -Path C:\path\to\file.txt -Value $filecontent
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-03
      • 1970-01-01
      • 2014-05-20
      • 2021-07-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多