programing

PowerShell에서 문자열(grep)을 선택할 때 일치하는 정규식만 반환하려면 어떻게 해야 합니까?

oldcodes 2023. 10. 26. 21:40
반응형

PowerShell에서 문자열(grep)을 선택할 때 일치하는 정규식만 반환하려면 어떻게 해야 합니까?

저는 파일에서 패턴을 찾으려고 합니다.다음을 사용하여 매치가 발생하면Select-String저는 전체 라인을 원하는 것이 아니라, 딱 맞는 부분을 원합니다.

이 작업에 사용할 수 있는 파라미터가 있습니까?

예를 들어,

그랬다면

select-string .-.-.

파일에는 다음과 같은 행이 포함되어 있습니다.

abc 1-2-3 abc

저는 전체 라인이 반송되는 대신 1-2-3만 결과를 받고 싶습니다.

파워셸을 알고 싶습니다.grep -o

아니면 그냥:

Select-String .-.-. .\test.txt -All | Select Matches

데이비드는 옳은 길을 가고 있습니다.[regex]는 시스템용 유형 가속기입니다.텍스트.정규식.Regex

[regex]$regex = '.-.-.'
$regex.Matches('abc 1-2-3 abc') | foreach-object {$_.Value}
$regex.Matches('abc 1-2-3 abc 4-5-6') | foreach-object {$_.Value}

그것이 너무 장황하면 함수로 포장할 수 있습니다.

Select-String은 사용할 수 있는 속성 일치를 반환합니다.모든 일치 항목을 가져오려면 -AllMatchs를 지정해야 합니다.그렇지 않으면 첫 번째 것만 반환됩니다.

내 테스트 파일 내용:

test test1 alk atest2 asdflkj alj test3 test
test test3 test4
test2

대본:

select-string -Path c:\temp\select-string1.txt -Pattern 'test\d' -AllMatches | % { $_.Matches } | % { $_.Value }

돌아온다

test1 #from line 1
test2 #from line 1
test3 #from line 1
test3 #from line 2
test4 #from line 2
test2 #from line 3

technet.microsoft.com 에서 문자열 선택

사람에게 낚시를 가르친다는 정신으로...

select-string 명령의 출력을 Get-member로 파이프링하여 개체에 어떤 속성이 있는지 확인할 수 있습니다.이렇게 하면 "Matches(일치)"가 표시되고 출력을 다음으로 파이핑하여 선택할 수 있습니다.| **Select-Object** Matches.

제 제안은 다음과 같은 것을 사용하는 것입니다: 라인 번호 선택, 파일 이름 선택, 일치

예를 들어, stej의 샘플에서:

sls .\test.txt -patt 'test\d' -All |select lineNumber,fileName,matches |ft -auto

LineNumber Filename Matches
---------- -------- -------
         1 test.txt {test1, test2, test3}
         2 test.txt {test3, test4}
         3 test.txt {test2}

위의 어떤 답변도 저에게 통하지 않았습니다.아래가 그랬습니다.

Get-Content -Path $pathToFile | Select-String -Pattern "'test\d'" | foreach {$_.Matches.Value}

Get-Content -Path $pathToFile | # Get-Content will divide into single lines for us

Select-String -Pattern "'test\d'" | # Define the Regex

{$}마다성냥.Value} # 개체의 일치 필드 값만 반환합니다. 여러 결과 일치를 허용합니다.

에 배관하는 대신%아니면select더 간단하게 사용할 수 있습니다..prop Member Enumeration 구문 - 여러 요소에서 마법처럼 작동합니다.

(Select-String .-.-. .\test.txt -All).Matches.Value

괄호 이하:

$m = Select-String .-.-. .\test.txt -All
$m.Matches.Value

ForEach operator를 사용하지 않으려면 파이프와Select -Expand

예를 들어 다음 경로만 가져오려면C:\, 다음을 사용할 수 있습니다.

Get-ChildItem | Select-String -Pattern "(C:\\)(.*)" | Select -Expand Matches | Select -Expand Groups | Where Name -eq 2 | Select -Expand Value

Where Name -eq 2지정한 정규 분포 패턴의 두 번째 일치만 선택합니다.

시스템을 사용할 수 있습니다.Text.Regular Expressions 네임스페이스:

http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx

언급URL : https://stackoverflow.com/questions/804754/how-do-i-return-only-the-matching-regular-expression-when-i-select-stringgrep

반응형