Dan
Dan

Reputation: 10171

Find and Replace character only in certain column positions in each line

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.

Upvotes: 3

Views: 7791

Answers (2)

Aaron Jensen
Aaron Jensen

Reputation: 26719

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)
    }

Upvotes: 3

zdan
zdan

Reputation: 29450

You can use the powershell -replace operator to replace the "." with "0". Then use substring as you do to build up the three portions of the string you're interested in to get the updated string. This will output an updated line for each line of your input.

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

Note that the -replace operator performs a regular expression match and the "." is a special regular expression character so you need to escape it with a "\".

Upvotes: 2

Related Questions