【问题标题】:Editing a file using search string in powershell在 powershell 中使用搜索字符串编辑文件
【发布时间】:2020-05-16 07:31:00
【问题描述】:

我在编写需要在输入文件中搜索字符串、将行内容复制到下一行并将字符串替换为另一个字符串的 powershell/批处理脚本时遇到困难。

例如,如果我的文件有以下内容

James is awesome.

Ryan is handsome.

Henry is a bad boy.

Jim is studious

当使用输入 "***Henry***""***Glenn***" 调用脚本时,输出应该是这样的

James is awesome.

Ryan is handsome.

***Henry*** is a bad boy.

***Glenn*** is a bad boy.

Jim is studious

【问题讨论】:

  • 可以接受 bash 解决方案吗?使用 sed 会相对容易

标签: string powershell replace


【解决方案1】:

这是在一行中查找单词的功能,如果找到与新单词重复的行。

Function ReplaceAndDuplicate([string[]]$drseus, $thing1, $thing2) {
  $drseus | % { 
    $_
    if ($_ -match $thing1) {
      $_ -replace $thing1, $thing2
    }
  }
}

用法:

ReplaceAndDuplicate (Get-Content C:\temp\file.txt) "Henry" "Glenn"

输出看起来像

James is awesome.
Ryan is handsome.
Henry is a bad boy.
Glenn is a bad boy.
Jim is studious

【讨论】:

  • 像魅力一样工作,感谢您的帮助。这正是我想要的。
  • 像魅力一样工作,感谢您的帮助。这正是我一直在寻找的。但是输出文件的大小要大得多(超过两倍),即使它添加了一行。虽然这不是一个大问题,但我们知道如何解决这个问题吗?
【解决方案2】:

试试这样:

$sel = Select-String -Path "FilePath" -Pattern "Henry"
If ($sel -ne $null) {
  $str = Select-String -Path "FilePath" -Pattern "^(Henry).*"
  $str = $str -replace "Henry", ""
  (Get-Content "FilePath") | Foreach {
        $_
        if ($_ -match "Henry")  {
            "`nJim $($str)"
        }
    } | Set-Content "FilePath"
}

【讨论】:

  • 这也有效,通过一些调整我能够得到结果。
  • 哪个更好?您必须通过单击刻度线来接受@Jawad 或我的答案(更好)。感谢您的帮助。
  • 两者都是正确的,只是另一个解决方案更接近解决方案。非常感谢您的帮助。
猜你喜欢
  • 2014-11-18
  • 1970-01-01
  • 1970-01-01
  • 2022-11-07
  • 2018-02-14
  • 2021-11-04
  • 1970-01-01
  • 2015-01-25
  • 1970-01-01
相关资源
最近更新 更多