1

In powershell I have different strings with e.g. the following content (3 different examples):

name_something_else_10
another_name_200
what_ever_you_like_1234567

I want to cut of everything after the last underscore. So what I want to get is the following:

name_something_else
another_name
what_ever_you_like

Each string is provided as a variable, and I need the result in a variable as well. What I am then looking for is how to cut the part of the string by using a function like follows:

$newString = CutOffEveryAfterUnderscore $oldString

2 Answers 2

6

You could use a regular expression ('_[^_]*$') combined with the replacefunction:

function Remove-LastUnderscore
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true,Position=0)]
        [string]
        $string
    )

    $string -replace '_[^_]*$'
}

Now you can use it like:

$newString =  Remove-LastUnderscore $oldString

or without a function:

$newString =  $oldString -replace '_[^_]*$'

Note: This solution also works with strings without an underscore.

Sign up to request clarification or add additional context in comments.

Comments

4

One way of doing it:

function Get-Prefix
{
    param($str)
    return $str.substring(0, $str.lastindexof('_'))
}

$strings = @("name_something_else_10",
    "another_name_200",
    "what_ever_you_like_1234567"
)

$strings | %{
    Get-Prefix $_
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.