0

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)

Zikato
  • 536
  • 9
  • 18
  • 1
    what have you tried so far? What is going wrong? Can you share some of the code? – frankM_DN Nov 04 '22 at 11:43
  • if you read it as one string, does it include newline `\n` characters? if so you could probably count the number of those before your desired string you can find the line number then if you count from the last `\n` to your desired string you could find column number. whether or not white space is preserved will provide a challenge as well. – frankM_DN Nov 04 '22 at 12:21

1 Answers1

1

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++
}
Shaneis
  • 1,065
  • 1
  • 11
  • 20