Poweshell analog grep -o command

Good afternoon! simple question, but can not find the answer. Which Powershell command replaces grep -o (which displays only the matched part of the string instead of the whole string)? I am trying to use Select-Object, but the full line is always displayed. For instance:

next line

<a id="tm_param1_text1_item_1" class="tm_param1param2_param3 xxx_zzz qqq_rrrr_www_vv_no_empty" >eeee <span id="ttt_xxx_zzz">0</span></a> 

use the following command:

 cat filename | grep -o '>[0-9]' | grep -o '[0-9]' 

output: 0

When I use Select-Object, I always see the full line (

+4
source share
4 answers

One of the methods:

 $a = '<a id="tm_param1_text1_item_1" class="tm_param1param2_param3 xxx_zzz qqq_rrrr_www_vv_no_empty" >eeee <span id="ttt_xxx_zzz">0</span></a>' $a -match '>([0-9])<' #returns true and populate the $matches automatic variable $matches[1] #returns 0 
+5
source

To select lines in the text, use select-string , not select-object . It will return a MatchInfo object. You can access matches by requesting the match property:

 $a = '<a id="tm_param1_text1_item_1" class="tm_param1param2_param3 xxx_zzz qqq_rrrr_www_vv_no_empty" >eeee <span id="ttt_xxx_zzz">0</span></a>' ($a | select-string '>[0-9]').matches[0].value # returns >0 
+3
source

The solutions that have been proposed so far give only the first match on each line. To fully emulate the grep -o behavior (which produces every match from each line), the following is required:

 Get-Content filename | Select-String '>([0-9])' -AllMatches | Select-Object -Expand Matches | % { $_.Groups[1].Value } 

Select-String -AllMatches returns all matches from the input string.

Select-Object -Expand Matches "disconnects" matches from the same row, so that all submatrices can be selected using $_.Groups[1] . Without this extension, the feed from the second string match will be $_.Groups[3] .

+1
source

InPowerShell v3:

 sls .\filename -pattern '^[0-9]' -AllMatches | % matches | % value 

Explanation: sls is an alias for Select-String. It takes a file name / path as well as a template as parameters. It produces "matches"

% matches selects all matches regardless of file, etc. % selects the value of each match

+1
source

Source: https://habr.com/ru/post/1484208/


All Articles