3

I'm trying to write a script to find all the periods in the first 11 characters or last 147 characters of each line (lines are fixed width of 193, so I'm attempting to ignore characters 12 through 45).

First I want a script that will just find all the periods from the first or last part of each line, but then if I find them I would like to replace all periods with 0's, but ignore periods on the 12th through 45th line and leaving those in place. It would scan all the *.dat files in the directory and create period free copies in a subfolder. So far I have:

$data = get-content "*.dat"
foreach($line in $data)
{
   $line.substring(0,12)
   $line.substring(46,147)
}

Then I run this with > Output.txt then do a select-string Output.txt -pattern ".". As you can see I'm a long ways from my goal as presently my program is mashing all the files together, and I haven't figured out how to do any replacement yet.

4

2 回答 2

3
Get-Item *.dat |
    ForEach-Object {
        $file = $_
        $_ | 
            Get-Content | 
            ForEach-Object {
                $beginning = $_.Substring(0,12) -replace '\.','0'
                $middle = $_.Substring(12,44)
                $end = $_.Substring(45,147) -replace '\.','0'
                '{0}{1}{2}' -f $beginning,$middle,$end
            } |
            Set-Content -Path (Join-Path $OutputDir $file.Name)
    }
于 2013-07-09T01:27:13.637 回答
2

您可以使用 powershell-replace运算符来替换“。” 与“0”。然后像您一样使用 substring 来构建您感兴趣的字符串的三个部分以获取更新的字符串。这将为您输入的每一行输出一个更新的行。

$data = get-content "*.dat"
foreach($line in $data)
{
    ($line.SubString(0,12) -replace "\.","0") + $line.SubString(13,34) + ($line.substring(46,147) -replace "\.","0")
}

请注意,-replace运算符执行正则表达式匹配和“。” 是一个特殊的正则表达式字符,因此您需要使用“\”对其进行转义。

于 2013-07-09T01:26:10.537 回答