Powershell用序列号替换字符串中的第26个字符

时间:2014-12-03 23:52:29

标签: powershell replace character substring

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

  2. 文件包含以下字符串:

  3. M453023455697RR23047230426485111814XXXXXX                                    
    
    RAPPAREL/ACCESSORIES               
    
    SHOES
    
    L03984798239409970924MM09709745340979XXXXXX
    
    M98802734207KK972839482326485111814XXXXXX
    

    1. 我的Powershell脚本:
    2. $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 {$_}  
      

3 个答案:

答案 0 :(得分:1)

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

使用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
}

答案 1 :(得分:1)

另一种可能性:

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
}

答案 2 :(得分:1)

另外一个选择只是为了yucks:

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&#39; MatchEvaluator但不幸的是,由于PowerShell处理回调的方式,这种方法很慢。