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

时间:2018-09-26 17:20:26

标签: powershell replace

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


文本18年5月9日
文字18-09-18
文本18-09-18

文本18年9月24日
文本18-10-18


我在.txt文件的第15行上尝试将其从24-09-18更改为2018年9月24日。
仅更改此内容,而不更改其他内容。

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

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

import java.util.Arrays;
import java.util.List;

@FunctionalInterface
interface Service { boolean test(); }

class CommonProcess {
  public static final CommonProcess INSTANCE = new CommonProcess();

  public boolean test(Service service) { return service.test(); }
}

class ProcessA implements Runnable {
  // specific project knows generic project -> no need to inject
  private static final CommonProcess commonProcess = CommonProcess.INSTANCE;
  private static final Service service = () -> false;

  public void run() {
    // generic project does not know specific project -> specifics are injected
    System.out.println(this.commonProcess.test(this.service));
  }
}

class ProcessB implements Runnable {
  // specific project knows generic project -> no need to inject
  private static final CommonProcess commonProcess = CommonProcess.INSTANCE;
  private static final Service service = () -> true;

  public void run() {
    // generic project does not know specific project -> specifics are injected
    System.out.println(this.commonProcess.test(this.service));
  }
}

class PlainApp {
  private static final List<Runnable> processes = Arrays.asList(new ProcessA(), new ProcessB());

  public static void main(String[] args) {
    for (Runnable process : processes)
      process.run();
  }
}

2 个答案:

答案 0 :(得分:2)

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数组的起源为零。如果要更改第十六行,请使用上面的代码。如果要更改第十五行,请使用$filecontent[14]而不是$filecontent[15]

答案 1 :(得分:0)

谢谢您的帮助对我有用,它照顾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 
}
相关问题