Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select all words from string except last (PowerShell)

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.

like image 328
Roel Avatar asked Feb 15 '12 18:02

Roel


People also ask

How do you split a string and get the last element in PowerShell?

In PowerShell string split, to get the last element from the string array, you can use the split operator. Use the -1 index to get the last element from substrings.

How do you split a string in PowerShell?

PowerShell uses the Split () function to split a string into multiple substrings. The function uses the specified delimiters to split the string into sub strings. The default character used to split the string is the whitespace.

How do you split an array in PowerShell?

In PowerShell, we can use the split operator (-Split) to split a string text into array of strings or substrings. The split operator uses whitespace as the default delimiter, but you can specify other characters, strings, patterns as the delimiter. We can also use a regular expression (regex) in the delimiter.

How do I remove an element from an array in PowerShell?

Removing objects from arrays should be simple, but the default collection type in Windows PowerShell, an object array (System. Object[]), has a fixed size. You can change objects in the array, but you can't add or delete them, because that would change the size of the array.


2 Answers

$string.SubString(0, $string.LastIndexOf(' '))
like image 92
Richard Avatar answered Sep 21 '22 02:09

Richard


Here's how I might do something like this.

$Sample = "String sample we can use"
$Split = $Sample.Split(" ")
[string]$split[0..($Split.count-2)]
like image 40
Geoff Guynn Avatar answered Sep 19 '22 02:09

Geoff Guynn