Recently i was looking for a way to select all the text between two brackets and ignore everything else in the string. This was necessary as i had a list of partial file name and i wanted a way of matching my list with a directory listing.
The use of '$_.split' command achieved this very nicely.
$text|%{$_.split('(')[1]}|%{$_.split(')')[0]}
The use of '$_.split' command achieved this very nicely.
How to i select specific text in a string?
$text='this is an (apple). it is red'
#The variable $text contains the word 'apple' between two opposite brackets.
$text|%{$_.split('(')[1]}|%{$_.split(')')[0]}
# $text is piped into a foreach loop spliting the string, removing everything before the first bracket (. It is then piped into a second foreach loop removing everything after the second bracket ).
apple # On screen the returned result is apple. This is useful if you are looking for partial file names, or a specific string within a string.
What does "%" mean in powershell syntax ?
The percentage sign '%' is used as an alias for 'ForEach-Object':
PS > get-alias -definition foreach-object
PS > get-alias -definition foreach-object
CommandType Name Definition
----------- ---- ----------
Alias % ForEach-Object
Alias foreach ForEach-Object
----------- ---- ----------
Alias % ForEach-Object
Alias foreach ForEach-Object
Comments
Post a Comment