【问题标题】:Replace a string but only the second occurence of that string替换一个字符串,但只替换该字符串的第二次出现
【发布时间】:2017-10-23 21:17:25
【问题描述】:

我的文件中有一些文本。

我使用Get-Content 读取文件,然后使用正则表达式-replace 查找模式并替换内容。这很完美,直到我遇到我需要替换该字符串的第二次出现而不是第一次或之后的任何情况(在这种情况下它只会出现两次)。

我想搜索“要查找的某个字符串”,然后仅替换该字符串的第二次出现。我已经搜索过,试图找到如何做到这一点的例子,但没有找到。我可以找到如何替换部分字符串,但不能找到完整字符串的全部单独出现。

这是替换所有出现的字符串的方法。

(gc file.txt) -replace "Some string to find", "some string changed") | sc file.txt

【问题讨论】:

  • 试试(gc file.txt) -replace "(str1.*?)str1", "${1}replaced" | sc file.txt。要仅匹配整个单词,请使用 "\b(str1\b.*?)\bstr1\b"

标签: regex powershell replace


【解决方案1】:

试试这个:

$find="world"
$replace="nice"
$string="the world is world, no?"
$pos=$string.IndexOf($find, $string.IndexOf($find)+1)

if ($pos -ne -1)
{
    "{0}{1}{2}" -f $string.Substring(0, $pos), $replace, $string.Substring($pos + $find.Length) 
}
else
{
   $string 
}

【讨论】:

  • 谢谢世界语。我还没有时间对此进行测试,但我今天会尝试这样做。您能解释一下 {0}{1}{2},这是指数组位置吗?谢谢。
  • 我试过这个,但在尝试读取文件并更改内容时它不起作用。我可以使用您的示例并且该示例有效,但是当我更改 $string = gc file.txt 时,尝试运行下一个 $pos= 命令时出现错误。找不到“IndexOf”的重载和参数计数:“2”。这可能是因为 Get-Content 将每一行加载为自己的字符串吗?谢谢。对不起
  • 你的 PowerShell 版本是多少?
  • 4.0 from Server 2012 R2 我想如果我们可以让它在 $string = "The world","is World","no?" 的地方工作这将解决我的问题。因为每个字符串现在都保存在变量中的单独“行”中。假设我的文件包含 *Red *Blue *Red *Green 现在我想找到第二个“Red”并将其替换为某些东西,但将第一个“Red”留在原处。如果所有内容都在一个字符串中,我知道该怎么做,但在这种情况下不是,它们是单独的行。我希望这可以更清楚地说明问题吗?
  • 我让这个与你的示例 Esperento57 一起工作。 :) 所以关键是 PowerShell 中的 Get-Content 将每个新行作为单独的字符串加载。所以从 PS 3.0 开始,我们现在可以使用 Get-Content “文本文件路径” - Raw。这将使它成为一个字符串。然后使用上面的示例,我能够完成这项工作。但是,是否可以解释“{0}{1}{2}” -f $string.Substring(0, $pos), $replace, $string.Substring($pos + $find.Length)?我不明白为什么会这样。谢谢。
【解决方案2】:

如果它不是可变的并且它总是第一次出现跳过,你可以简单地做类似的事情

mystring.substring(mystring.indexOf("string to match")).replace("string to match", "some string changed")

(js示例)

【讨论】:

  • 谢谢 FluffyNights。虽然使用 mystring.substring,但如何将它与 get-content (gc) 一起使用?我希望 PowerShell 读取内容,并尝试将其保存回来。我会使用:(gc file.txt)| mystring.substring....?谢谢。
  • 我不熟悉powershell,但据我所知,方法几乎相同,所以你可能会使用 mystring.Substring(mystring.indexOf(...)).Replace(... )。如果你没有让它运行,结帐4sysops.com/archives/…
【解决方案3】:

如果您想替换文本的第二个单词,请尝试像这样替换(要查找的单词使用标点符号):

$find="world", "world.", "world;", "world," , "world?", "world!", "world:"
$replace="nice"
$string="the world is world, no?"
$array=$string -split " "
$Nbfounded=0
$result=""


foreach ($item in $array)
{
    $Founded=$false

    if ($item -in $find)
    {
       $Nbfounded++
       $Founded=$true 
    }


    if ($Founded -and $Nbfounded -eq 2)
    {
        $result=$result + ' ' + $replace
    }
    else
    {
        $result=$result + ' ' + $item
    }

}

$result.TrimStart()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-25
    • 2016-11-02
    • 2019-07-02
    • 2022-10-07
    • 2020-07-10
    相关资源
    最近更新 更多