从字符串匹配返回行号

时间:2016-01-07 20:09:18

标签: powershell

我试图将字符串搜索返回的行号转换为变量。

过程

  1. 运行目录中的过滤文件
  2. 打开每个文件并搜索字符串
  3. 存储与文字匹配的行号
  4. 我得到了要返回的行号,但是不知道如何从这里开始使用它。

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

1 个答案:

答案 0 :(得分:3)

在这方面做了一些工作。这适用于我需要的功能。改进?

# 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 


}