Select all words from string except last (PowerShell)

19,184

Solution 1

Here's how I might do something like this.

$Sample = "String sample we can use"
$Split = $Sample.Split(" ")
[string]$split[0..($Split.count-2)]

Solution 2

$string.SubString(0, $string.LastIndexOf(' '))

Solution 3

You can do it like this:

$test -replace "\S*\s*$"

Solution 4

This will remove the last word even if there are trailing spaces. It also preserves multiple spaces between words, and removes spaces before the last word.

'this   is   a    test ' -replace '^(.+\b)\s+\S+\s*','$1'

It doesn't remove the last word if the string is a single word.

Share:
19,184
Roel
Author by

Roel

Updated on October 02, 2022

Comments

  • Roel
    Roel over 1 year

    So what I am trying to achieve is selecting all words from a given string, except the last one. So I have a few strings;

    On The Rocks
    The Rocks
    Major Bananas
    

    I want to select all words, except the last one from every string. I figured out I could use split() to take every word as separate. Though I can't figure it out any further.

    Thanks in advance.