-2

I would like to replace the n'th character in a file with another - so for example you have

Type:1BANKFROMBANK1TO2 -> Type:2BANKFROMBANK1TO2
Type:2BANKFROMBANK1TO2 -> Type:2BANKFROMBANK1TO2
Type:3BANKFROMBANK1TO2 -> Type:2BANKFROMBANK1TO2
Type:4BANKFROMBANK1TO2 -> Type:2BANKFROMBANK1TO2

I do not know what the value will be, but I know at what place it will be - so for this example the 6th character.

When attempting to do it like this:

$Replace = Get-ChildItem "C:\temp\" -Filter "xfil*"
Foreach ($file in $Replace) {
(Get-Content $File.fullname).replace((Get-Content $File.fullname)[5],'x') | Set-Content -Path $file.FullName
}

It replaces every occurence of the character which is expected but not exactly what I want- how do I go around that?

  • No unfortunately, this is looking for a match and then replacing the first occurence. I'm looking not for a match but for a certain "spot" in the string - basically the 26th character, no matter what it is. – Sebastian Wiszowaty Nov 02 '20 at 09:56
  • Please [edit] the question and add better examples. As of now, the transformation from `1asfasasf1asfa -> 2sdfdsfdsfd1sf` has much more changes than a single char at position _n_. Maybe also explain what you are really trying to do, there might be a better way overall. – vonPryz Nov 02 '20 at 10:07
  • I have edited the example to more reflect that it is actually a single character change and not the text after it. – Sebastian Wiszowaty Nov 02 '20 at 10:12

2 Answers2

0

Your examples do not match the description of the question. However, from your comment, I gather you simply want to replace the 26th character with another.

To do that, read the file in as single string and do the replacement:

$charIndex   = 26   # the character index. Remember this counts from 0
$replaceWith = 'x'  # the character to put in the $charIndex place
Get-ChildItem "C:\Temp" -Filter "xfil*" -File | ForEach-Object {
    $content = Get-Content -Path $_.FullName -Raw
    $content.Replace($content[$charIndex], $replaceWith) | Set-Content -Path $_.FullName
}

Alternative

Get-ChildItem "C:\Temp" -Filter "xfil*" -File | ForEach-Object {
    $content = Get-Content -Path $_.FullName -Raw
    if ($content.Length -gt $charIndex) {
        "{0}$replaceWith{1}" -f $content.Substring(0, $charIndex), 
                                $content.Substring($charIndex + 1) |
        Set-Content -Path $_.FullName
    }
}
Theo
  • 57,719
  • 8
  • 24
  • 41
-1

It can also be achieved with this one liner:

$Content = Get-Content -path $file.fullname
$Replace = $Content.Remove(22,1).Insert(22,$ReplaceNumber) | Set-content $file.fullname