I have a file containing a large number of occurrences of the string Guid="GUID HERE"
(where GUID HERE
is a unique GUID at each occurrence) and I want to replace every existing GUID with a new unique GUID.
This is on a Windows development machine, so I can generate unique GUIDs with uuidgen.exe
(which produces a GUID on stdout every time it is run). I have sed
and such available (but no awk
oddly enough).
I am basically trying to figure out if it is possible (and if so, how) to use the output of a command-line program as the replacement text in a sed
substitution expression so that I can make this replacement with a minimum of effort on my part. I don't need to use sed
-- if there's another way to do it, such as some crazy vim
-fu or some other program, that would work as well -- but I'd prefer solutions that utilize a minimal set of *nix programs since I'm not really on *nix machines.
To be clear, if I have a file like this:
etc etc Guid="A" etc etc Guid="B"
I would like it to become this:
etc etc Guid="C" etc etc Guid="D"
where A, B, C, D are actual GUIDs, of course.
(for example, I have seen xargs
used for things similar to this, but it's not available on the machines I need this to run on, either. I could install it if it's really the only way, although I'd rather not)
I rewrote the C# solution in PowerShell. I figured it would be easier for you to run a powershell script then compile a C# exe.
Steps for using this:
## 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"