Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

analog command grep -o in Powershell

What command in Powershell replaces grep -o (which displays only the matched portion of a line instead of a whole line) ? i try use Select-Object but it always display full line. For example:

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 next command:

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

output: 0

When i use Select-Object i always see full line (

like image 576
user2441498 Avatar asked Jun 03 '13 13:06

user2441498


People also ask

Can you use grep in PowerShell?

Grep is used in Linux to search for regular expressions in text strings and files. There's no grep cmdlet in PowerShell, but the Select-String cmdlet can be used to achieve the same results. The Windows command line has the findstr command, a grep equivalent for Windows.

What is grep in shell script?

In Linux and Unix Systems Grep, short for “global regular expression print”, is a command used in searching and matching text files contained in the regular expressions.

Can we use sed in PowerShell?

Sed examples Summary: By putting these filters into the top of my scripts (or using them when I launch PowerShell) I've been able to take most of the times where I would need a grep or a sed and utilize this approach to accomplish the same type of functionality.


2 Answers

One way is:

$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
like image 77
CB. Avatar answered Sep 25 '22 10:09

CB.


For selecting strings in text, use select-string rather than select-object. It will return a MatchInfo object. You can access the matches by querying the matches 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
like image 21
jon Z Avatar answered Sep 22 '22 10:09

jon Z