我在编写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发布于 2020-01-30 16:42:55
这是在一行中查找单词的函数,如果发现它与新单词重复行的话。
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发布于 2020-01-30 16:43:42
就像这样:
$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"
}https://stackoverflow.com/questions/59990167
复制相似问题