programing

Grep - f와 동등한 PowerShell

powerit 2023. 4. 8. 09:54
반응형

Grep - f와 동등한 PowerShell

다음과 같은 PowerShell을 찾고 있습니다.grep --file=filename모르면.grepfilename은 각 행에 대조하는 정규 표현 패턴이 있는 텍스트파일입니다

뭔가 확실한 걸 놓치고 있는 건지도 모르지만Select-String이 방법은 없는 것 같습니다.

-Pattern매개 변수Select-String는 패턴 배열을 지원합니다.그래서 당신이 찾는 것은:

Get-Content .\doc.txt | Select-String -Pattern (Get-Content .\regex.txt)

텍스트 파일을 검색합니다.doc.txt의 모든 정규식(한 줄에 하나씩)을 사용함으로써regex.txt

PS) new-alias grep findstr
PS) C:\WINDOWS> ls | grep -I -N exe

105:-a---        2006-11-02     13:34      49680 twunk_16.exe
106:-a---        2006-11-02     13:34      31232 twunk_32.exe
109:-a---        2006-09-18     23:43     256192 winhelp.exe
110:-a---        2006-11-02     10:45       9216 winhlp32.exe

PS) grep /?

GREP에 익숙하지 않지만 Select-String을 사용하면 다음 작업을 수행할 수 있습니다.

Get-ChildItem filename.txt | Select-String -Pattern <regexPattern>

Get-Content를 사용하여 이 작업을 수행할 수도 있습니다.

(Get-Content filename.txt) -match 'pattern'

Powershell이 있는 파일에서 텍스트를 찾느라 같은 문제가 있었습니다.Linux 환경에 가능한 한 가까이 접근하기 위해 다음 방법을 사용했습니다.

이것이 누군가에게 도움이 되기를 바랍니다.

PowerShell:

PS) new-alias grep findstr
PS) ls -r *.txt | cat | grep "some random string"

설명:

ls       - lists all files
-r       - recursively (in all files and folders and subfolders)
*.txt    - only .txt files
|        - pipe the (ls) results to next command (cat)
cat      - show contents of files comming from (ls)
|        - pipe the (cat) results to next command (grep)
grep     - search contents from (cat) for "some random string" (alias to findstr)

네, 이 방법도 유효합니다.

PS) ls -r *.txt | cat | findstr "some random string"

이 링크에서 꽤 좋은 답을 찾았습니다.https://www.thomasmaurer.ch/2011/03/powershell-search-for-string-or-grep-for-powershell/

하지만 본질적으로는 다음과 같습니다.

Select-String -Path "C:\file\Path\*.txt" -Pattern "^Enter REGEX Here$"

이를 통해 디렉토리 파일 검색(* 또는 파일만 지정할 수 있음)과 파일 컨텐츠 검색이 모두 GREP와 매우 유사한 PowerShell의 한 줄에 제공됩니다.출력은 다음과 같습니다.

doc.txt:31: Enter REGEX Here
HelloWorld.txt:13: Enter REGEX Here

파이프라인 출력에 grep를 사용하는 경우 PowerShell의 "filter" 및 "alias"를 통해 가능한 방법을 알아봅니다(grep 파일도 비슷해야 함).

먼저 필터를 정의합니다.

filter Filter-Object ([string]$pattern) {
    Out-String -InputObject $_ -Stream | Select-String -Pattern "$pattern"
}

에일리어스를 정의합니다.


    New-Alias -Name grep -Value Filter-Object

마지막으로 이전 필터와 에일리어스를 프로파일에 추가합니다.

$Home [ My ]Documents \PowerShell\MicrosoftPowerShell_profile.ps1

PS를 재기동하면, 다음과 같이 사용할 수 있습니다.

alias | grep 'disp'


레퍼런스

  1. 에일리어스:Set-Alias 여기서 New-Alias 여기서

  2. Filter(특수 기능)여기서

  3. 프로파일(bash의 .bashrc와 같음): 여기

  4. out-string(이것열쇠입니다)
    PowerShell Output은 객체 기반이기 때문에
    오브젝트를 문자열로 변환하고 문자열을 GREP합니다.

  5. Select-String 여기:
    문자열 및 파일에서 텍스트 찾기

이 질문에는 이미 답변이 있습니다만, Windows에는 Linux WSL용 Windows Subsystem이 있다는 것을 추가하고 싶습니다.

를 들어 실행 인 Elasicsearch라는 이름의 서비스가 있는지 확인하고 싶다면 powershell의 아래 부분과 같은 작업을 수행할 수 있습니다.

net start | grep Elasticsearch

그러나 select-String에는 이 옵션이 없는 것 같습니다.

맞아요.PowerShell은 *nix 쉘 툴셋의 클론이 아닙니다.

그러나 직접 이와 같은 것을 구축하는 것은 어렵지 않습니다.

$regexes = Get-Content RegexFile.txt | 
           Foreach-Object { new-object System.Text.RegularExpressions.Regex $_ }

$fileList | Get-Content | Where-Object {
  foreach ($r in $regexes) {
    if ($r.IsMatch($_)) {
      $true
      break
    }
  }
  $false
}

아마도?

[regex]$regex = (get-content <regex file> |
foreach {
          '(?:{0})' -f $_
        }) -join '|'

Get-Content <filespec> -ReadCount 10000 |
 foreach {
           if ($_ -match $regex)
             {
              $true
              break
             }
         }

언급URL : https://stackoverflow.com/questions/15199321/powershell-equivalent-to-grep-f

반응형