PowerShell 정규식 문제
이것은 내 첫 번째 게시물이며 다른 게시물을 읽고 검색하여 필요한 것을 찾을 수있는 경향이 있지만 이것은 나를 패배 시켰습니다. Powershell에서 정규식을 사용하여 텍스트 파일에서 데이터를 찾으려고합니다.
샘플 텍스트 파일 :( 샘플 텍스트 파일에는 해당 줄 끝까지 공백이 있습니다.)
Impression CONCLUSION:
Impression
Impression CONCLUSION:
Impression SomeData
Impression CONCLUSION:
Impression SomeOtherData
Impression CONCLUSION:
Impression
결론이있는 줄 뒤에 두 번째 줄이 비어있는 위치를 찾고 있습니다.
이것이 내 간단한 시도의 기반이었습니다.
Get-Content -Path "C:\temp\Log\Conclusion.txt" | Select-String -Pattern "CONCLUSION:\s*\r\n\s*Impression\s*\r\n\s*Impression" -Context 1, 1
\ r \ n이있는 모든 항목은 결과를 반환하지 않습니다. 나는 \ r과 \ n을 모두 시도했고, 콘텐츠를 Raw로 얻으려고 시도했지만 전체 파일을 다시 출력합니다. 도움을 주셔서 감사합니다.
업데이트 : 모두의 답변에 감사드립니다. 결론이 나고 비어있는 줄을 찾으려고했다고 구체적으로 말 했어야했습니다. 결국 Get-Content -Raw를 사용하여 시작하는 일에 대한 카운트를 얻었습니다. 내 샘플 데이터가 약간 변경되어 인상이라는 단어가 포함 된 빈 줄이 추가되었습니다. 이름 / 위치 노출 결론 :
노출 노출
이 코드는 나에게 카운트를 얻을 수 있었다 :( 다른 포럼 게시물에서 가져 오기 / 수정 됨, 나는 이것에 대해 인정하지 않습니다)
$ search_string = "\ s 결론 : \ s \ r \ n \ s Impression \ s \ r \ n \ s Impression \ s \ r \ n \ s Impression \ s \ r \ n"$ file_path = "C : \ temp \ Log \ Conclusion.txt "$string = (Get-Content -raw -Path $file_path | 선택 문자열$search_string -AllMatches | % { $_.matches}). count
나는 여전히 Raw를 사용하지 않을 때만 작동하는 더 많은 데이터를 인쇄하는 방법을 연구하고 있으며, 컨텍스트를 사용하여 결론 위의 줄을 잡으려고 계획했지만 raw는 모든 것을 한 줄로 가져 오므로 작동하지 않습니다. 도움을 주셔서 다시 한 번 감사드립니다. 누구든지 Raw를 사용하지 않고 \ r \ n을 사용할 수있는 방법에 대한 팁이 더 있으면 알려주세요.
답변
이것이 powershell과 얼마나 잘 작동하는지 잘 모르겠지만,이 기회를주세요. (*CRLF)CONCLUSION:\sImpression\s\s
https://regex101.com/r/d6Pm2k/1
내 추악한 무차별 대입 공격은 다음과 같습니다.
$blankRows = @() $targetRows = @()
$rowNum = 0 $foundRows = @()
$myFile = Get-Content $thisFile
Foreach($thisRow in $myFile){
$rowNum++ if($thisRow -eq "Impression"){$blankRows += $rowNum}
if ($thisRow -match 'CONCLUSION'){$targetRows += $rowNum} } Foreach($blrw in $blankRows){ if ($targetRows -contains ($blrw-1)){$foundRows += $blrw} } $foundRows
왜 이렇게하지 않습니까?
# Create some sample data file
@'
Impression CONCLUSION:
Impression
Impression CONCLUSION:
Impression SomeData
Impression CONCLUSION:
Impression SomeOtherData
Impression CONCLUSION:
Impression
'@ |
Out-File -FilePath 'D:\Temp\Imprestion.txt' -Force
Get-Content -Path 'D:\Temp\Imprestion.txt'
# Results
<#
Impression CONCLUSION:
Impression
Impression CONCLUSION:
Impression SomeData
Impression CONCLUSION:
Impression SomeOtherData
Impression CONCLUSION:
Impression
#>
# Import the sample data file as a CSV, use the space as a Delimiter
Import-Csv -Path 'D:\Temp\Imprestion.txt' -Delimiter ' ' -Header Property, Value
# Results
<#
Property Value
-------- -----
Impression CONCLUSION:
Impression
Impression CONCLUSION:
Impression SomeData
Impression CONCLUSION:
Impression SomeOtherData
Impression CONCLUSION:
Impression
#>
# Filter by the Value property
Import-Csv -Path 'D:\Temp\Imprestion.txt' -Delimiter ' ' -Header Property, Value |
Where-Object -Property Value -EQ $null # Results <# Property Value -------- ----- Impression Impression #> # Using Select-String and a RegEx 'Not Match' Select-String -Path 'D:\Temp\Imprestion.txt' -Pattern '^((?!Impression [a-zA-Z]).)*$'
# Results
<#
D:\Temp\Imprestion.txt:2:Impression
D:\Temp\Imprestion.txt:3:
D:\Temp\Imprestion.txt:6:
D:\Temp\Imprestion.txt:9:
D:\Temp\Imprestion.txt:11:Impression
#>
# Using Select-String and RegEx match
Select-String -Path 'D:\Temp\Imprestion.txt' -Pattern '^Impression\s*$'
# Results
<#
D:\Temp\Imprestion.txt:2:Impression
D:\Temp\Imprestion.txt:11:Impression
#>
설명:
- ^는 문자열 앵커의 시작입니다.
- $는 문자열 앵커의 끝입니다.
- \ s는 공백 문자 클래스입니다.
- 0 또는 그 이상의 반복입니다.
정확히 무엇을 캡처해야하는지, 완전히 빈 줄 또는 Impression뒤에 데이터가 있거나 없는 줄은 아직 확실하지 않습니다 .
그러나 문서에 따르면 Get-Contnet :
- 파일의 경우 콘텐츠는 한 번에 한 줄씩 읽고 각 콘텐츠 줄을 나타내는 개체 컬렉션을 반환합니다.
따라서 <newline>문자는 문자열 배열의 요소 구분자로 "사용"됩니다.
시험:
Get-Content -Path "C:\temp\Log\Conclusion.txt" | gm
(Get-Content -Path "C:\temp\Log\Conclusion.txt").Count
따라서 <newline>작성된 코드와 절대 일치하지 않을 것 입니다.
당신이 사용할 수있는 -Raw하나의 긴 문자열로 파일을 치료하는 paramaeter를 <newline>문자 나 배열을 검색하는데 논리를 재 작성.
또한 Select-string에 대한 문서 는 파일을 직접 가져 와서 Get-Content.
최신 정보
어떤 라인을 출력하고 싶은지 아직 잘 모르겠지만, 여기에 당신이 요구하고 있다고 생각 하는 스켈레톤 샘플이 있습니다. 내 가정은 다음과 같습니다.
- 찾고있는 라인은 "Impression"다음에 텍스트가없는 라인입니다 (문자 그대로 또는 데이터인지 명시하십시오).
- 일치하는 항목이 발견되면 출력 파일에 대해 이전 행이 캡처됩니다.
$File = Get-Content -Path "C:\temp\Log\Conclusion.txt" $OutLines = @()
$EmptyMatch = '^Impression\s*$'
$i = 0 ForEach ( $line in $File ) { If ( $line -match $EmptyMatch ) { $OutLines += $File[ $i - 1 ]
}
$i++ } $OutLines | Set-Content 'c:\MyStuff\OutFile.txt'
Add