gpt4 book ai didi

shell - 从命令行用新的 GUID 替换文件中的所有 GUID

转载 作者:行者123 更新时间:2023-12-04 13:35:27 48 4
gpt4 key购买 nike

我有一个文件,其中包含大量出现的字符串 Guid="GUID HERE" (其中 GUID HERE 在每次出现时都是唯一的 GUID),我想用新的唯一 GUID 替换每个现有的 GUID。

这是在 Windows 开发机器上,所以我可以用 uuidgen.exe 生成唯一的 GUID。 (每次运行时都会在 stdout 上生成一个 GUID)。我有 sed和这样的可用(但没有 awk 很奇怪)。

我基本上是想弄清楚是否可以(如果可以,如何)使用命令行程序的输出作为 sed 中的替换文本。替换表达式,以便我可以以最少的努力进行此替换。我不需要使用 sed -- 如果有其他方法可以做到,比如一些疯狂的 vim -fu 或其他一些程序,它也可以工作——但我更喜欢使用最少的 *nix 程序集的解决方案,因为我不是真的在 *nix 机器上。

需要明确的是,如果我有这样的文件:

etc etc Guid="A" etc etc Guid="B"

我希望它变成这样:
etc etc Guid="C" etc etc Guid="D"

当然,其中 A、B、C、D 是实际的 GUID。

(例如,我已经看到 xargs 用于类似的事情,但它在我需要它运行的机器上也不可用。如果它真的是唯一的方法,我可以安装它,尽管我宁愿不)

最佳答案

我在 PowerShell 中重写了 C# 解决方案。我认为运行 powershell 脚本然后编译 C# exe 对您来说会更容易。

使用步骤:

  • 下载/安装powershell
  • 将代码保存在下面的某个地方,命名为 GuidSwap.ps1
  • 修改 $filename 和 $outputFilename 变量以满足您的需要
  • 运行 powershell -noexit c:\location\to\guidswap.ps1

  • ## GuidSwap.ps1
    ##
    ## Reads a file, finds any GUIDs in the file, and swaps them for a NewGUID
    ##

    $filename = "d:\test.txt"
    $outputFilename = "d:\test_new.txt"

    $text = [string]::join([environment]::newline, (get-content -path $filename))

    $sbNew = new-object system.text.stringBuilder

    $pattern = "[a-fA-F0-9]{8}-([a-fA-F0-9]{4}-){3}[a-fA-F0-9]{12}"

    $lastStart = 0
    $null = ([regex]::matches($text, $pattern) | %{
    $sbNew.Append($text.Substring($lastStart, $_.Index - $lastStart))
    $guid = [system.guid]::newguid()
    $sbNew.Append($guid)
    $lastStart = $_.Index + $_.Length
    })
    $null = $sbNew.Append($text.Substring($lastStart))

    $sbNew.ToString() | out-file -encoding ASCII $outputFilename

    Write-Output "Done"

    关于shell - 从命令行用新的 GUID 替换文件中的所有 GUID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2201740/

    48 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com