Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell Split string into variables [duplicate]

Tags:

powershell

I have a line a text and I want the first word to be a variable, the second to be a second but all the rest to be consider one single var.

For example splitting Mary had a little lamb would result in:

  • $var[1] = Mary
  • $var[2] = had
  • $var[4] = a little lamb

How can I achieve this when I split by space?

like image 628
Alexandru Lazar Avatar asked Jul 12 '17 14:07

Alexandru Lazar


3 Answers

If you know the exact length of the first two words you can use .substring. Otherwise, you can use -Split and then use -join after assigning the first two array entries to your variables.

$mySplit = "alpha bravo charlie delta" -split " "
$var1 = $mySplit[0]
$var2 = $mySplit[1]
$var3 = $mySplit[2..($mySplit.length+2)] -join " "

The above example for $var3 grabs the array created by the -split and gets every entry except the first 2. The -join will then join the array entries back together into a single string separating each entry by a space.

like image 168
Jason Snell Avatar answered Nov 17 '22 09:11

Jason Snell


$a="Mary had a little lamb"
$v1,$v2,$v3=$a.split(" ",3)

The split is what turns a string into an array, the "3" is the limit of how many parts to split into, and the variable list to the left of "=" is what make the result to end up in corresponding variables.

PS > $v3
a little lamb 
PS >
like image 29
Vesper Avatar answered Nov 17 '22 11:11

Vesper


Simply tell Split the number of elements to return:

$string = "Mary had a little lamb"
$var = $string.Split(" ",3)

Which will return:

Mary
had
a little lamb

You can then reference each element individually:

$var[0]
$var[1]
$var[2]
like image 1
henrycarteruk Avatar answered Nov 17 '22 11:11

henrycarteruk