所以我有这个输入文件(没有扩展名):
0 1 2 3 4 5 ###6#### _7______ 8 9 0 1 2 3 ###4##__
012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456
0202XXXX TESTS1 XX DRN CODE123 010TESTS 0000000001481500000014832000000148150000001481700000014832+
0202XXXX TESTS1 TEST11 DRN CODE123 010TESTS 0000000000336400000003364000000033640000000336400000003364+
0202XXXX TESTS1 XXX YYYYYY PN N2 CODE123 010TESTS 0000000000118500000001206000000011600000000118300000001205+
0202XXXX TESTS1 ZZZZZZZZZ DRN CODE123 010TESTS 0000000004188300000041883000000412400000004156200000041240+
0202XXXX TESTS1 PPP MKLRTR PN CODE123 010TESTS 0000000000000000000000000000000000000000000000000000000000/
0202XXXX TESTS1 GGG TEST ON ED CODE123 010TESTS 0000000000095000000001024000000009500000000098700000001024-
我想从那里获得3个值并打印出具有特定格式的新文件。
我正在尝试使用substring选项,但却无法像我预期的那样在输出文件上看到结果,那么请问这个代码有什么问题呢?
我希望将输出视为:
1 2 3 4 5
1234567890123456789012345678901234567890123456789012345
CODE123 17.98
CODE12 2.37
CODE 2.70
CODE12 2.73
CODE123 13.39
但是使用下面的代码我得到没有列的结果,这一切都搞砸了。
$InputFile = D:\Test\inputfile.txt
$outFile = D:\Test\outfile.txt
$Pattern = "010TESTS"
$spaces1 = " ";
$spaces2 = " ";
$dot = "."
$rec = 0
(gc $InputFile) | ? {$_.trim() -ne "" } | select-string -pattern $Pattern -AllMatches | Set-Content $outFile
$file = gc $outFile
$Test = $file.Substring(69, 8) #this should give me the value 010TESTS
foreach ($line in $file) {
if ($Test -eq "010TESTS"){
$Value1 = $file.Substring(57, 8)
$Value2 = $file.Substring(137, 6).TrimStart('0') #to remove leading zeroes
$Value3 = $file.Substring(143, 2)
if ( ! ($Value1 -eq "" -and $Value2 -eq "00") ) {
$FinalFile += ($spaces1 + $Value1 + $spaces2 + $Value2 + $dot + $Value3).Split("`n") #here I need the values on each line
}
}
}
$FinalFile| Set-Content $outFile
答案 0 :(得分:1)
ruler
$spaces = " " * 21
-f
格式字符串进行输出,请参阅脚本。$InputFile = 'D:\Test\inputfile.txt'
$outFile = 'D:\Test\outfile.txt'
$Pattern = "010TESTS"
Get-Content $InputFile | Select-String -Pattern $Pattern | ForEach-Object {
$Line = [string]$_
$Line.Substring(70, 8) #this should give me the value 010TESTS
$Value1 = $Line.Substring(57, 8)
$Value2 = [double]$Line.Substring(137, 8) / 100
if ( $Value1 -and $Value2 ) {
"{0,25}{1,30:N2}" -f $Value1,$Value2 | Out-File $OutFile -Append
}
}
.substring
-f
此示例输出由于我的语言环境而产生小数点逗号。 (手动添加标尺)
1 2 3 4 5
1234567890123456789012345678901234567890123456789012345
CODE123 14,83
CODE123 3,36
CODE123 1,20
CODE123 41,24
CODE123 1,02