Pawel G.
Pawel G.

Reputation: 13

Powershell substring cutting

Is there a function in Powershell that would cut values according to given formatting mask?

Lets use for example $test = "Value 14, Code 57"

Cut-Substring("Value $val, Code $code",$test)

As the result I would like to receive $val = 14 and $code = 57.

If not, is there an even more powerful tool allowing to access fields next to given labels?

Upvotes: 1

Views: 434

Answers (2)

Doug Finke
Doug Finke

Reputation: 6823

An alternative.

$test = "Value 14, Code 57"
$val,$code=$test -split ',' | ForEach {($_.Trim() -split ' ')[1]}
'$val={0} and $code={1}' -f $val,$code

# Prints
# $val=14 and $code=57

Upvotes: 0

manojlds
manojlds

Reputation: 301477

Um, regex?

$test = "Value 14, Code 57"
$test -match 'Value (\d+), Code (\d+)'
$matches[1] #14
$matches[2] #57

The power of regexes should allow you to tweak it to your needs.

Upvotes: 5

Related Questions