MojoTom
MojoTom

Reputation: 13

Powershell - Replacing first 3 characters of each line in file

Here's my little script that I can't get to work.

$test = gc -path old.txt;

 for ($i=0; $i -le 14; $i++)
 {  $charCount= $test[$i].length;
    $zero = "0";
    $checkSum  = $charCount + 2;
    $newValue  = $zero + $checkSum.ToString();
  $test[$i] -replace "$test[$i].substring(2)", $newValue ;
  };
sc -path new.txt

The idea would be to create a little checksum at the start of each line.

Data should transform from this:

XXX80006302
XXX810000175
XXX92063
XXX921802.10

to this:

01380006302
014810000175
01192063
014921802.10

Upvotes: 0

Views: 1383

Answers (1)

AdminOfThings
AdminOfThings

Reputation: 25001

I think you can simplify this using the string format operator.

$lines = Get-Content -Path old.txt
$output = foreach ($line in $lines){
    "{0:d3}{1}" -f ($line.length+2),$line.substring(3)
}
$output | Set-Content new.txt

If you want to use the -replace operator, you can do the following:

$lines = Get-Content -Path old.txt
$output = foreach ($line in $lines){
    $checksum = "{0:d3}" -f ($line.length+2)
    $line -replace '^.{3}',$checksum
}
$output | Set-Content new.txt

Since -replace uses regex matching, ^.{3} matches the first three characters. ^ is the beginning of the string. . is any character. {3} matches the previous regex match a total of 3 times. So any character (.) three ({3}) times. -replace only replaces what is matched and then returns the remaining string as is.

Upvotes: 4

Related Questions