gpt4 book ai didi

powershell - 从字符串匹配返回行号

转载 作者:行者123 更新时间:2023-12-02 23:12:13 27 4
gpt4 key购买 nike

我正在尝试将字符串搜索返回的行号放入变量中。

过程

  1. 运行目录中过滤后的文件
  2. 打开每个文件并搜索字符串
  3. 存储行号与文本匹配

我得到要返回的行号,但不知道如何从这里使用它。

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

最佳答案

在这方面做了更多的工作。这可以满足我的需要。改进?

# 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


}

关于powershell - 从字符串匹配返回行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34664231/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com