Sergio Ramos
Sergio Ramos

Reputation: 123

Cut everything after dash in Powershell

I've got the array of string looks like that:

Cola-12-0-15-300-122
Pepsi-123-34-543
7_Up-rrr-12-2342-2
Fanta_Mineral-1212-fgdfg-33

And I need to retrieve from these values just the first words till the dash.

So I will have

Cola
Pepsi
7_up
Fanta_Mineral

Upvotes: 0

Views: 67

Answers (2)

Vish
Vish

Reputation: 466

Try this:

$Strings = @(
    'Cola-12-0-15-300-122',
    'Pepsi-123-34-543',
    '7_Up-rrr-12-2342-2',
    'Fanta_Mineral-1212-fgdfg-33'
)

$FirstWord = $Strings | ForEach-Object {
    ($_ -split '-')[0]
}

$FirstWord

Upvotes: 1

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174710

You could use the -replace operator to remove everything after the first - with -replace '-.*'

$strings = -split @'
Pepsi-123-34-543
7_Up-rrr-12-2342-2
Fanta_Mineral-1212-fgdfg-33
'@

$strings -replace '-.*'

Outputs:

Cola
Pepsi
7_Up
Fanta_Mineral

Upvotes: 4

Related Questions