【问题标题】:Powershell replace 26th character in a string with a sequence numberPowershell用序列号替换字符串中的第26个字符
【发布时间】:2014-12-03 23:52:28
【问题描述】:

 

  1. 我想替换以“M”开头的字符串的第 26 个字符,并且我想在后面的任何字符串中放入一个从零开始的序列号和 Sequence# + 1。

    李>
  2. 文件包含这些字符串:

M453023455697RR23047230426485111814XXXXXX                                    

RAPPAREL/ACCESSORIES               

SHOES

L03984798239409970924MM09709745340979XXXXXX

M98802734207KK972839482326485111814XXXXXX

 

  1. 我的 Powershell 脚本:
$SequenceStart = 1
$String = "M"
$str2 = "$xfiles.substring(0,24)"
$str3 = "$xfiles.substring(25)"
$str4 = "$xfiles.substring(26,53)"
$str5 = "$xfiles.substring(0,80)"
$Line = "$str2""$str+1""$str4"


$xfiles = Get-ChildItem $InFiles
Write-Host "Found " ($xfiles | Measure-Object).count " files to process"


If (($xfiles | Measure-Object).count -gt 0) {
    foreach ($xfile in $xfiles)
    {
        Write-Host "Processing file: $xFile`r"

        $cnt = $SequenceStart

        $content = Get-Content -path $xfile

        $content | foreach {
            If ($_.Contains($String)) {
                $_ -replace $String, $Line}
            else {$_}  

【问题讨论】:

  • 您有问题吗?
  • 您的代码也不完整,因为我们看不到 $InFiles 的声明位置......并不是说它真的会影响问题,但可能还有其他内容缺失,例如 if 语句上的右大括号和foreach。你没说到底有什么问题?
  • 是的,这个脚本不起作用,我想知道如何实现它。我也忘了声明一个变量$ str = $ str3。但即使在此之后它也不起作用。谢谢
  • $InFiles = 包含数据的文件 CDMS.txt 的路径。我想知道如何编写 IF 语句,或者是否可以调整此脚本。任何提示将不胜感激。谢谢
  • 序列号...是否代表M行的每个匹配项?所以文件中的第 5 M 行的序列号是 5?它是替换第 26 个字符还是将其向下推。完成后,您将如何处理数据?将其写回同一个文件?

标签: powershell replace character substring


【解决方案1】:

另一种选择只是为了讨厌:

foreach ($xFile in $xFiles) {
    Write-Progress -Activity "Processing file: $xFile"
    $counter = 0
    Get-Content $xFile | Foreach {
        [regex]::replace($_, '(^M.{24}).(.*)', 
            {param($m) $m.Groups[1].Value + ($global:counter++) + $m.Groups[2].Value})
    } | Out-File $xFile.FullName
}

一定要喜欢好的 ol' MatchEvaluator,但不幸的是,由于 PowerShell 处理回调的方式,这种方法很慢。

【讨论】:

  • 谢谢大家。所有解决方案都有效,但我使用了 Keith 建议的解决方案。谢谢基思。
【解决方案2】:

工作无聊...好吧,我知道的最简单的方法是:

使用 Get-Content 读取文件,遍历所有行,如果它以 M 开头,则替换并增加计数器。

foreach ($xfile in $xfiles)
{
    Write-Host "Processing file: $xFile`r"
    $counter = 0
    (Get-Content $xfile | ForEach{
        If($_ -match "^m"){$_ -replace "(?<=^.{25})(.)",$counter;$counter++}else{$_}
    })|out-file $xfile.fullname
}

【讨论】:

  • 干得好。好久没见了正则表达式将成为搜索。我也没想到用它来替换。
  • 在 MS 作为供应商获得了一份新工作,所以我一直在忙着学习。不过应该更经常地回来=)
【解决方案3】:

另一种可能性:

foreach ($xfile in $xfiles)
{
    Write-Host "Processing file: $xFile`r"
    $counter = 0
    (Get-Content $xfile | ForEach{
      if ($_ -match '^(M.{24}).(.+)')
        {'{0}{1}{2}' -f $matches[1],$counter++,$matches[2]}
      else {$_}  
    })|out-file $xfile.fullname
}

【讨论】:

  • 嗯,你先$Counter = 0 然后$i++。我从不记得我可以同时递增和使用变量。我想我可以将我的 $counter;$counter++ 缩短为 $counter++
  • 错过了。谢谢你的收获。编写代码需要更多工作,但可能更直观,具体取决于您对正则表达式的熟悉程度。
猜你喜欢
  • 2020-03-14
  • 2014-08-28
  • 2013-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
相关资源
最近更新 更多