Home > Net >  How do I Split a string in Powershell
How do I Split a string in Powershell

Time:09-13

Suppose there is a string named as (ai-somename-someid) and it is stored in say

$x='ai-somename-someid'

Now I want to extract (somename)from the given string and pass it into another variable by using split(I am using the below script)

$y = $x.split("-")   
$y 

It is giving me the output as

ai  
somename   
someid  

but I would like to have only

somename

  

as the output.

CodePudding user response:

You can directly pass y[1] as a variable name for someone.

$x= "ai-somename-someid"
$y =  $x.split("-")
$y[1]

CodePudding user response:

There's a couple of way you can do that : If you only want one item this is the most straight forward way to do it. Simply cut your string and reference the id of the element you want to save.

$x="ai-somename-someid"
$y=$x.split("-")[1]

or you could do this instead if you are interested in keeping the other parts :

$x="ai-somename-someid"
$z,$y,$v=$x.split("-")

In this exemple $z will have ai, $y somename and $v someid.

If you are only interested in keeping some of the resulting string you can do this :

$x="ai-somename-someid"
$z,$y,$null=$x.split("-")

In this exemple $z will have ai, $y somename and everything after that goes to the trash.

CodePudding user response:

Or using the split operator. This is really about picking the 2nd element of an array. The count starts at 0.

'ai-somename-someid' -split '-' | select-object -index 1
somename

-split on the left side will split on whitespace.

(-split 'ai somename  someid')[1]
somename
  • Related