Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split string by string in Powershell

Tags:

powershell

People also ask

How do I split a string into string?

Use the Split method when the substrings you want are separated by a known delimiting character (or characters). Regular expressions are useful when the string conforms to a fixed pattern. Use the IndexOf and Substring methods in conjunction when you don't want to extract all of the substrings in a string.

How do I cut text in PowerShell?

One of the most common ways to trim strings in PowerShell is by using the trim() method. Like all of the other trimming methods in PowerShell, the trim() method is a member of the System. String . NET class.

What does $_ mean in PowerShell?

The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.


The -split operator uses the string to split, instead of a chararray like Split():

$string = "5637144576, messag<>est<<>>5637145326, 1<<>>5637145328, 0"
$separator = "<<>>"
$string -split $separator

5637144576, messag<>est
5637145326, 1
5637145328, 0

If you want to use the Split() method with a string, you need the $seperator to be a stringarray with one element, and also specify a stringsplitoptions value. You can see this by checking its definition:

$string.Split

OverloadDefinitions                                                                                
-------------------                                                                                
string[] Split(Params char[] separator)                                                            
string[] Split(char[] separator, int count)                                                        
string[] Split(char[] separator, System.StringSplitOptions options)                                
string[] Split(char[] separator, int count, System.StringSplitOptions options)                     

#This one
string[] Split(string[] separator, System.StringSplitOptions options)      
string[] Split(string[] separator, int count, System.StringSplitOptions options)


$string = "5637144576, messag<>est<<>>5637145326, 1<<>>5637145328, 0"
$separator = [string[]]@("<<>>")
$string.Split($separator, [System.StringSplitOptions]::RemoveEmptyEntries)

5637144576, messag<>est
5637145326, 1
5637145328, 0

EDIT: As @RomanKuzmin pointed out, -split splits using regex-patterns by default. So be aware to escape special characters (ex. . which in regex is "any character"). You could also force simplematch to disable regex-matching like:

$separator = "<<>>"
$string -split $separator, 0, "simplematch"

Read more about -split here.


Instaed of using Split method, you can use split operator. So your code will be like this:

$string -split '<<>>'

Sometimes PowerShell looks exactly like C# and at others, well you know...

It could also be used thus:

# A dummy text file
$text = @'
abc=3135066977,8701416400

def=8763026853,6433607660

xyz=3135066977,9878763344
'@ -split [Environment]::NewLine,[StringSplitOptions]"RemoveEmptyEntries"

"`nBefore `n------`n"

$text

"`nAfter `n-----`n"

# Do whatever with this
foreach ($line in $text)
{
    $line.Replace("3135066977","6660985845")
}

EDIT 2020-05-23: I've moved my code to GitHub, here, where I've made updates to cover a few edge cases: https://github.com/franklesniak/PowerShell_Resources/blob/master/Split-StringOnLiteralString.ps1


You can use the -split operator, but it expects RegEx. Furthermore, the -split operator is only available on Windows PowerShell v3+, so we need a different method if you want something that is universally compatible with all versions of PowerShell.

A [regex] object has a Split() method that can handle this as well, but again, it expects RegEx as the "splitter". To get around this, we can use a second [regex] object and call the Escape() method to convert our literal string "splitter" into escaped RegEx.

Wrapping all this up into an easy to use function that works back to PowerShell v1 and also works on PowerShell Core 6.x.

function Split-StringOnLiteralString
{
    trap
    {
        Write-Error "An error occurred using the Split-StringOnLiteralString function. This was most likely caused by the arguments supplied not being strings"
    }

    if ($args.Length -ne 2) `
    {
        Write-Error "Split-StringOnLiteralString was called without supplying two arguments. The first argument should be the string to be split, and the second should be the string or character on which to split the string."
    } `
    else `
    {
        if (($args[0]).GetType().Name -ne "String") `
        {
            Write-Warning "The first argument supplied to Split-StringOnLiteralString was not a string. It will be attempted to be converted to a string. To avoid this warning, cast arguments to a string before calling Split-StringOnLiteralString."
            $strToSplit = [string]$args[0]
        } `
        else `
        {
            $strToSplit = $args[0]
        }

        if ((($args[1]).GetType().Name -ne "String") -and (($args[1]).GetType().Name -ne "Char")) `
        {
            Write-Warning "The second argument supplied to Split-StringOnLiteralString was not a string. It will be attempted to be converted to a string. To avoid this warning, cast arguments to a string before calling Split-StringOnLiteralString."
            $strSplitter = [string]$args[1]
        } `
        elseif (($args[1]).GetType().Name -eq "Char") `
        {
            $strSplitter = [string]$args[1]
        } `
        else `
        {
            $strSplitter = $args[1]
        }

        $strSplitterInRegEx = [regex]::Escape($strSplitter)

        [regex]::Split($strToSplit, $strSplitterInRegEx)
    }
}

Now, using the earlier example:

PS C:\Users\username> Split-StringOnLiteralString "5637144576, messag<>est<<>>5637145326, 1<<>>5637145328, 0" "<<>>"
5637144576, messag<>est
5637145326, 1
5637145328, 0

Volla!