Home > Enterprise >  In a file content - find a line and column from the offset
In a file content - find a line and column from the offset

Time:11-05

I have a file called C:\FindPos.txt with this content:

Lorem ipsum dolor sit amet,   
    consectetur adipiscing elit, sed do  
eiusmod tempor incididunt ut.

I have an Offset and want to find the Line and Column

  1. The word incididunt ends on Offset = 98. I want to find Ln = 3 and Col = 26 enter image description here

Current experiments:

$path = 'C:\FindPos.txt'

$oneStringcontent = [System.IO.File]::ReadAllText($path)
$fileContent = get-content -Path $path

$StartLine = 3
$StartColumn = 26
$StartOffset = 98

write-host "$($oneStringcontent[$StartOffset 1])"


$fileContent |  ForEach-Object {
    $currentLine = $_.ReadCount
    if ($currentLine -eq $StartLine) {
        write-host "Line $StartLine | Column = $StartColumn | Line = $($_) | Char = $($_[$StartColumn  1])"
    }
}

If I read the file as one string, I can grab the correct character from the array, but no idea how to turn that into Ln/Col.

If I read it line by line, I have the opposite problem (also, the character column position doesn't match)

CodePudding user response:

The below should, hopefully, work for you.

$Path = 'C:\FindPos.txt'
$Content = Get-Content -Path $Path

$Column = $OffSet = 1
$Line = 0

foreach ($Char in $Content.ToCharArray()) {
    $CurrentLine = $Content[$Line]
  
    [PSCustomObject] @{
        Token = $Char
        OffSet = $OffSet
        Line = $Line   1
        Column = $Column
    }

    if ($Column -ge $CurrentLine.Length) { $Column = 0; $Line   }

    $OffSet  
    $Column  
}
  • Related