Eamon
Eamon

Reputation: 71

Return line number from string match

I'm trying to get the line number returned on a string search into a variable.

Process

  1. run through filtered files in a directory
  2. open each file and search for string
  3. store line number with text match

I get the line number to return, but don't know how to work with it from here.

# Pull files from source directory with extension filter
Get-ChildItem $SourceDirectory -Filter $OutputFileExtension -Recurse |
    ForEach-Object {
        Select-String $_ -Pattern $TargetString |
            Select-Object -ExpandProperty 'LineNumber'
    }

Upvotes: 3

Views: 13780

Answers (1)

Eamon
Eamon

Reputation: 71

Did a little more work on this. This functions for what I need. Improvements?

# Pull files from source directory with extension filter
Get-ChildItem $SourceDirectory -Filter $OutputFileExtension |


ForEach-Object {

    #Assign variable for total lines in file
    $measure = Get-Content $_.FullName | Measure-Object
    $TotalLinesInFile = $measure.count


    #Assign variable to the line number where $TargetString is found
    $LineNumber = Select-String $_ -Pattern $TargetString | Select-Object -ExpandProperty 'LineNumber'
    Write-Host "Line where string is found: "$LineNumber

    #Store the line number where deletion begins
    $BeginDelete = $Linenumber - $LinesToDeleteBefore
    Write-Host "Line Begin Delete: "$BeginDelete

    #Store the line number where deletion ends
    $EndDelete = $LineNumber + $LinesToDeleteAfter 
    Write-Host "Line End Delete: "$EndDelete

    #Assign variable for export file
    $OutputFile = $ExportDirectory + $_.Name

    #Get file content for update
    $FileContent = Get-Content $_.FullName
    Write-Host "FileContent: " $FileContent

    #Remove unwanted lines by excluding them from the new file
    $NewFileContent = $FileContent[0..$BeginDelete] + $FileContent[($EndDelete + $LineToDeleteAfter)..$TotalLinesInFile] | Set-Content $OutputFile 


}

Upvotes: 4

Related Questions