使用命令行中的新GUID替换文件中的所有GUID

时间:2010-02-04 17:21:46

标签: shell replace sed guid text-processing

我有一个包含大量字符串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用于与此类似的事情,但它在我需要运行的机器上不可用。我可以安装它,如果它真的是唯一的方法,虽然我宁愿不)

5 个答案:

答案 0 :(得分:7)

我在PowerShell中重写了C#解决方案。我认为你运行一个PowerShell脚本然后编译一个C#exe会更容易。

使用它的步骤:

  1. 下载/安装powershell
  2. 将代码保存在某处,名为GuidSwap.ps1
  3. 修改$ filename和$ outputFilename变量以满足您的需求
  4. 运行 powershell -noexit c:\ location \ to \ guidswap.ps1

  5. ## 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"
    

答案 1 :(得分:2)

您是否愿意编译C#控制台应用程序来执行此操作?我快速地掀起了这个。它将文件名作为命令行参数,查找看起来像GUID的任何内容,将其替换为新的GUID,并写入文件的新内容。

看看:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace GUIDSwap
{
    class Program
    {
        static int Main(string[] args)
        {
            try
            {
                if (args.Length == 0) throw new ApplicationException("No filename specified");

                string filename = args[0];
                filename = filename.TrimStart(new char[] { '"' }).TrimEnd(new char[] { '"' });

                if (!File.Exists(filename)) throw new ApplicationException("File not found");

                StreamReader sr = new StreamReader(filename);
                string text = sr.ReadToEnd();
                sr.Close();

                StringBuilder sbNew = new StringBuilder();

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

                int lastStart = 0;
                foreach (Match m in Regex.Matches(text, pattern))
                {
                    sbNew.Append(text.Substring(lastStart, m.Index - lastStart));
                    sbNew.Append(Guid.NewGuid().ToString());
                    lastStart = m.Index + m.Length;
                }

                sbNew.Append(text.Substring(lastStart));

                StreamWriter sw = new StreamWriter(filename, false);
                sw.Write(sbNew.ToString());
                sw.Flush();
                sw.Close();

                return 0;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return 1;
            }
        }
    }
}

答案 2 :(得分:1)

我一直在寻找一种方法来替换Visual Studio解决方案中的所有GUID,因此我接受了这个StackOverflow问题(GuidSwap.ps1)的答案并对其进行了扩展,以便脚本跟踪多个文件中引用的GUID 。下面的标题中显示了一个示例。

<#
    .Synopsis
    Replace all GUIDs in specified files under a root folder, carefully keeping track 
    of how GUIDs are referenced in different files (e.g. Visual Studio solution).

    Loosely based on GuidSwap.ps1:
    http://stackoverflow.com/questions/2201740/replacing-all-guids-in-a-file-with-new-guids-from-the-command-line

    .NOTES
    Version:        1.0
    Author:         Joe Zamora (blog.idmware.com)
    Creation Date:  2016-03-01
    Purpose/Change: Initial script development

    .EXAMPLE
    .\ReplaceGuids.ps1 "C:\Code\IDMware" -FileNamePatterns @("*.sln","*.csproj","*.cs") -Verbose -WhatIf
#>

# Add common parameters to the script.
[CmdletBinding()]
param(
    $RootFolder
    ,$LogFolder='.'
    ,[String[]]$FileNamePatterns
    ,[switch]$WhatIf
)
$global:WhatIf = $WhatIf.IsPresent

# Change directory to the location of this script.
$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath
cd $dir
$ScriptName = $MyInvocation.MyCommand.Name

If(!($RootFolder))
{
    Write-Host @"
Usage: $ScriptName  -RootFolder <RootFolder> [Options]

Options:
    -LogFolder <LogFolder>                      Defaults to location of script.

    -FileNamePatterns @(*.ext1, *.ext2, ...)    Defaults to all files (*).

    -WhatIf                                     Test run without replacements.

    -Verbose                                    Standard Powershell flags.
    -Debug
"@
    Exit
}

if ($LogFolder -and !(Test-Path "$LogFolder" -PathType Container))
{
    Write-Host "No such folder: '$LogFolder'"
    Exit
}

<#
    .Synopsis
    This code snippet gets all the files in $Path that contain the specified pattern.
    Based on this sample:
    http://www.adminarsenal.com/admin-arsenal-blog/powershell-searching-through-files-for-matching-strings/
#>
function Enumerate-FilesContainingPattern {
[CmdletBinding()]
param(
    $Path=(throw 'Path cannot be empty.')
    ,$Pattern=(throw 'Pattern cannot be empty.')
    ,[String[]]$FileNamePatterns=$null
)
    $PathArray = @()
    if (!$FileNamePatterns) {
        $FileNamePatterns = @("*")
    }

    ForEach ($FileNamePattern in $FileNamePatterns) {
        Get-ChildItem $Path -Recurse -Filter $FileNamePattern |
        Where-Object { $_.Attributes -ne "Directory"} |
        ForEach-Object {
            If (Get-Content $_.FullName | Select-String -Pattern $Pattern) {
                $PathArray += $_.FullName
            }
        }
    }
    $PathArray
} <# function Enumerate-FilesContainingPattern #>

# Timestamps and performance.
$stopWatch = [System.Diagnostics.Stopwatch]::StartNew()
$startTime = Get-Date
Write-Verbose @"

--- SCRIPT BEGIN $ScriptName $startTime ---

"@

# Begin by finding all files under the root folder that contain a GUID pattern.
$GuidRegexPattern = "[a-fA-F0-9]{8}-([a-fA-F0-9]{4}-){3}[a-fA-F0-9]{12}"
$FileList = Enumerate-FilesContainingPattern $RootFolder $GuidRegexPattern $FileNamePatterns

$LogFilePrefix = "{0}-{1}" -f $ScriptName, $startTime.ToString("yyyy-MM-dd_HH-mm-ss")
$FileListLogFile = Join-Path $LogFolder "$LogFilePrefix-FileList.txt"
$FileList | ForEach-Object {$_ | Out-File $FileListLogFile -Append}
Write-Host "File list log file:`r`n$FileListLogFile"
cat $FileListLogFile | %{Write-Verbose $_}

# Next, do a read-only loop over the files and build a mapping table of old to new GUIDs.
$guidMap = @{}
foreach ($filePath in $FileList)
{
    $text = [string]::join([environment]::newline, (get-content -path $filePath))
    Foreach ($match in [regex]::matches($text, $GuidRegexPattern)) {
        $oldGuid = $match.Value.ToUpper()
        if (!$guidMap.ContainsKey($oldGuid)) {
            $newGuid = [System.Guid]::newguid().ToString().ToUpper()
            $guidMap[$oldGuid] = $newGuid
        }
    }
}

$GuidMapLogFile = Join-Path $LogFolder "$LogFilePrefix-GuidMap.csv"
"OldGuid,NewGuid" | Out-File $GuidMapLogFile
$guidMap.Keys | % { "$_,$($guidMap[$_])" | Out-File $GuidMapLogFile -Append }
Write-Host "GUID map log file:`r`n$GuidMapLogFile"
cat $GuidMapLogFile | %{Write-Verbose $_}

# Finally, do the search-and-replace.
foreach ($filePath in $FileList) {
    Write-Verbose "Processing $filePath"
    $newText = New-Object System.Text.StringBuilder
    cat $filePath | % { 
        $original = $_
        $new = $_
        $isMatch = $false
        $matches = [regex]::Matches($new, $GuidRegexPattern)
        foreach ($match in $matches) {
            $isMatch = $true
            $new = $new -ireplace $match.Value, $guidMap[$match.Value.ToString().ToUpper()]
        }        
        $newText.AppendLine($new) | Out-Null
        if ($isMatch) {
            $msg = "Old: $original`r`nNew: $new"
            if ($global:WhatIf) {
                Write-Host "What if:`r`n$msg"
            } else {
                Write-Verbose "`r`n$msg"
            }
        }
    }
    if (!$global:WhatIf) {
        $newText.ToString() | Set-Content $filePath
    }
}

# Timestamps and performance.
$endTime = Get-Date
Write-Verbose @"

--- SCRIPT END $ScriptName $endTime ---

Total elapsed: $($stopWatch.Elapsed)
"@

答案 3 :(得分:0)

您可以先将uid捕获到变量中,然后再执行sed?

@echo off
setlocal enabledelayedexpansion
for /f %%x in ('uuidgen.exe') do (
        set uid=%%x
)
sed -e "s/Guid=\"\(.*\)\"/Guid=\"!uid!\"/g" file

答案 4 :(得分:0)

我非常喜欢BigJoe714的解决方案。我更进一步找到了所有特定的扩展文件,并替换了所有的GUID。

<pre>
<code>
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace AllGuidSwap
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                if (args.Length == 0) throw new ApplicationException("No filename specified");

                string directory = args[0]; //Path
                string extensionToFind = args[1]; //Extension to find

                if (!Directory.Exists(directory)) throw new ApplicationException("directory not found");

                var allFiles = Directory.GetFiles(directory).Where(a => a.EndsWith(extensionToFind));

                foreach (var filename in allFiles)
                {
                    if (!File.Exists(filename)) throw new ApplicationException("File not found");

                    var sr = new StreamReader(filename);
                    var text = sr.ReadToEnd();
                    sr.Close();

                    var sbNew = new StringBuilder();

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

                    var lastStart = 0;
                    foreach (Match m in Regex.Matches(text, pattern))
                    {
                        sbNew.Append(text.Substring(lastStart, m.Index - lastStart));
                        sbNew.Append(Guid.NewGuid().ToString().ToUpperInvariant());
                        lastStart = m.Index + m.Length;
                    }

                    sbNew.Append(text.Substring(lastStart));

                    var sw = new StreamWriter(filename, false);
                    sw.Write(sbNew.ToString());
                    sw.Flush();
                    sw.Close();
                }

                Console.WriteLine("Successful");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.ReadKey();
        }
    }
}

</code>
</pre>