Home > other >  Cut everything after dash in Powershell
Cut everything after dash in Powershell

Time:11-22

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

CodePudding user response:

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

CodePudding user response:

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
  • Related