PowerShell splits a string into the first occurrence of a substring / character

I have a string that I want to split into two parts. The first part is before the comma ( , ), and the second part is everything after the comma (including commas).

I already managed to get the first part before the comma in the $Header variable, but I don’t know how to get the fragments after the first comma in one big line, so it contains

 $Content = "Text 1,Text 2,Text 3,Text 4," 

There may be more text visible here, for example, text 5, text 6, ..

 $String = "Header text,Text 1,Text 2,Text 3,Text 4," $Header = $String.Split(',')[0] //<-- $Header = "Header text" 
+8
string split powershell
source share
4 answers

Try something like:

 $Content=$String.Split([string[]]"$Header,", [StringSplitOptions]"None")[1] 

As you split line by line, you use a different signature for the split function.

For basic use, only one argument is required, the separator character (more information about this can be found here ). However, to use strings, the signature is as follows:

 System.String[] Split(String[] separator, StringSplitOptions options) 

This is why you should specify your string as an array of strings. In this case, we use the None parameter, but you can find other parameters available in the split documentation.

Finally, since the value of $Heasder, is at the beginning of your $String , you need to catch the second element of the resulting array.

+2
source share

The PowerShell -split supports specifying the maximum number of substrings returned, i.e. the number of substrings returned. After the template is split, specify the number of rows you want to return:

 $header,$columns = "Header text,Text 1,Text 2,Text 3,Text 4," -split ',',2 
+13
source share

This alternative solution uses PowerShell's ability to spread arrays across multiple variables with a single assignment. Note, however, that the -split operator -split split into each comma, and the built-in PowerShell conversion from the array back to String will merge the elements together. It is not as efficient as String.Split , but in your example it is insignificant.

 $OFS = ',' $Content = 'Header text,Text 1,Text 2,Text 3,Text 4,' [String]$Header,[String]$Rest = $Content -split $OFS $OFS = ' ' Write-Host "Header = $Header" Write-Host "Rest = $Rest" 

Finally, $OFS is a special variable in PowerShell that determines which character will be used when attaching array elements to a single line. By default, this is a space. But it can be changed to anything.

0
source share

Aaron method is the best, but I offer my solution

 $array="Header text,Text 1,Text 2,Text 3,Text 4," -split ',' $array[0],($array[1..($array.Length -1)] -join ",") 
0
source share

All Articles