Select-string - more than one pattern (only strings that contain all patterns )

Welcome Forums General PowerShell Q&A Select-string - more than one pattern (only strings that contain all patterns )

Viewing 6 reply threads
  • Author
    Posts
    • #195860
      Participant
      Topics: 17
      Replies: 14
      Points: 88
      Rank: Member

      I'm trying to get only the strings that contain more than one pattern .

      I have file called newfile.txt that its content is :

      server-syslog-02
      serverlog-02

      Get-ChildItem newfile.txt | Select-String -Pattern 02,syslog output is :

      newfile.txt:1:server-syslog-02
      newfile.txt:2:serverlog-02

       

      I've tried Get-ChildItem newfile.txt | % { ($_ | Select-String -Pattern 02 ) -and ($_ | Select-String syslog) } , which is  output is Boolean or the same thing with Get-content or with where .    nothing worked

       

      How can I get only the string that contain both pattern 02  and syslog   ?

      (only server-syslog-02 )

       

       

    • #195863
      Participant
      Topics: 17
      Replies: 14
      Points: 88
      Rank: Member

      Get-ChildItem newfile.txt | Select-String -Pattern 02 |Select-String syslog                 did the job

      but is there a way to save both patterns on a variable and use the var , instead of the select-string "chain"  ?

    • #195890
      Participant
      Topics: 2
      Replies: 1693
      Points: 3,368
      Helping Hand
      Rank: Community Hero

      You could use regex look-aheads like this:

      Select-String -Path D:\sample\search-text.txt -Pattern '(?=.*syslog)(?=.*02)'
    • #195896
      js
      Participant
      Topics: 27
      Replies: 739
      Points: 2,013
      Helping Hand
      Rank: Community Hero

      I think you mean where-object not foreach-object:

      get-content newfile-txt | where-object { ($_ | Select-String -Pattern 02 ) -and 
        ($_ | Select-String syslog) }
      
      newfile.txt:1:server-syslog-02
      
    • #195902
      Participant
      Topics: 5
      Replies: 285
      Points: 213
      Helping Hand
      Rank: Participant
      # Find all lines containing strings 'syslog' and '02'
      (Get-Content newfile.txt) -match '.*syslog.*02.*'
      
    • #196085
      Participant
      Topics: 17
      Replies: 14
      Points: 88
      Rank: Member

      That worked . thanks

    • #196091
      Participant
      Topics: 17
      Replies: 14
      Points: 88
      Rank: Member

      Olaf and random commandline , your solution worked

      js ,  I tried your solution but with  one stupid  mistake  – I forgot to change Get-ChildItem to get-content

      Thanks everyone

Viewing 6 reply threads
  • You must be logged in to reply to this topic.