psg20
psg20

Reputation: 31

Powershell Remove Strings from each line after a match

I have a log file with below contents and I need to replace everything after a match inclusive of the match criteria as well using powershell script

Log File:

 - ABCD,1234,12 Percent (Total: 12 / 100)
 - DEFG,1234,32 Percent (Total: 32 / 100)
 - HIJK,1234,77 Percent (Total: 77 / 100)
 - QWER,1234, (Total: 77 / 100)

I would like to get output like below

 - ABCD,1234,12 Percent
 - DEFG,1234,32 Percent
 - HIJK,1234,77 Percent
 - QWER,1234,0 Percent

I tried regex commands which replaces but not inclusive of the match criteria in powershell and substring never worked too

Thanks

Upvotes: 0

Views: 707

Answers (3)

Theo
Theo

Reputation: 61028

Or use switch:

$result = switch -Regex -File 'Path\To\The\LogFile.log' {
    '^(.+\d+\sPercent).*' { $matches[1] }
    '(,\s\([^)]+\))$'     { $_ -replace [regex]::Escape($matches[1]), ',0 Percent'}
    default { $_ }
}

# show on screen
$result

# write to (new) file
$result | Set-Content -Path 'Path\To\The\NewLogFile.log'

Output:

 - ABCD,1234,12 Percent
 - DEFG,1234,32 Percent
 - HIJK,1234,77 Percent
 - QWER,1234,0 Percent

Upvotes: 0

pmooo00
pmooo00

Reputation: 31

I may not be fully understanding your question, but are you looking for something like this?:

$Text = 'ABCD,1234,12 Percent (Total: 12 / 100)', 
'DEFG,1234,32 Percent (Total: 32 / 100)', 
'HIJK,1234,77 Percent (Total: 77 / 100)', 
'QWER,1234, (Total: 77 / 100)'
$text | Foreach-Object {
    $_ = $_ -replace ' \(.*'
    if ($_ -notlike "*Percent*"){
        $_ = $_ + "0 Percent"
    }
    $_
}

Output:

ABCD,1234,12 Percent 
DEFG,1234,32 Percent 
HIJK,1234,77 Percent 
QWER,1234,0 Percent

Upvotes: 2

Joma
Joma

Reputation: 3859

Input

ABCD,1234,12 Percent (Total: 12 / 100)
DEFG,1234,32 Percent (Total: 32 / 100)
HIJK,1234,77 Percent (Total: 77 / 100)
QWER,1234, (Total: 77 / 100)

Script

Get-Content ".\Log.txt" | ForEach-Object { 
    $result = "$_".Substring(0, "$_".IndexOf("(") -1)
    if(!$result.EndsWith("Percent"))
    {
        $result += "0 Percent"
    }
    $result
}

Output

ABCD,1234,12 Percent
DEFG,1234,32 Percent
HIJK,1234,77 Percent
QWER,1234,0 Percent

code

Upvotes: 0

Related Questions