[英]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
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:如果要使用
-replace
运算符,可以执行以下操作:
$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.由于
-replace
使用正则表达式匹配,所以^.{3}
匹配前三个字符。 ^
is the beginning of the string. ^
是字符串的开头。 .
is any character.是任何字符。
{3}
matches the previous regex match a total of 3 times. {3}
匹配前一个正则表达式匹配共 3 次。 So any character ( .
) three ( {3}
) times.所以任何字符 (
.
) 三 ( {3}
) 次。 -replace
only replaces what is matched and then returns the remaining string as is. -replace
仅替换匹配的内容,然后按原样返回剩余的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.