Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell Split a String On First Occurrence of Substring/Character

Tags:

I have a string that I want to split up in 2 pieces. The first piece is before the comma (,) and the second piece is all stuff after the comma (including the commas).

I already managed to retrieve the first piece before the comma in the variable $Header, but I don't know how to retrieve the pieces after the first comma in one big string.

$string = "Header text,Text 1,Text 2,Text 3,Text 4,"

$header = $string.Split(',')[0] # $Header = "Header text"

$content = "Text 1,Text 2,Text 3,Text 4," 
# There might be more text then visible here, like say Text 5, Text 6, ..
like image 925
DarkLite1 Avatar asked Aug 19 '14 12:08

DarkLite1


People also ask

How do you split a string on the first occurrence of certain characters?

To split a JavaScript string only on the first occurrence of a character, call the slice() method on the string, passing it the index of the character + 1 as a parameter. The slice method will return the portion of the string after the first occurrence of the character.

How do you split on the first occurrence?

Use the str. split() method with maxsplit set to 1 to split a string on the first occurrence, e.g. my_str. split('-', 1) . The split() method only performs a single split when the maxsplit argument is set to 1 .

How do you split a string in PowerShell?

Split() function. The . Split() function splits the input string into the multiple substrings based on the delimiters, and it returns the array, and the array contains each element of the input string. By default, the function splits the string based on the whitespace characters like space, tabs, and line-breaks.

How do you split a string at a certain character?

To split a string with specific character as delimiter in Java, call split() method on the string object, and pass the specific character as argument to the split() method. The method returns a String Array with the splits as elements in the array.


1 Answers

PowerShell's -split operator supports specifying the maximum number of sub-strings to return, i.e. how many sub-strings to return. After the pattern to split on, give the number of strings you want back:

$header,$content = "Header text,Text 1,Text 2,Text 3,Text 4," -split ',',2
like image 82
Aaron Jensen Avatar answered Sep 28 '22 19:09

Aaron Jensen