dagda1
dagda1

Reputation: 28820

Replace text in pipe

I have the following script I am using to delete git merged branches:

function Remove-MergedBranches
{
  git branch -a --merged |
    ForEach-Object { $_.Trim() } |
    Where-Object {$_ -NotMatch "^\*"} |
    Where-Object {-not ( $_ -Like "*master" )} |
    Where-Object {-not ( $_ -Like "*develop" )} |
    Where-Object {-not ( $_ -Like "*dev" )} |
    % {$_.replace("/remotes","")} |
    ForEach-Object { git branch -d $_ }
}

The replace is not working.

A branch might be remotes/origin/tg-training-section

Upvotes: 1

Views: 5913

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 58961

You wan't to replace /remotes in remotes/origin/tg-training-section which doesn't match (it doesnt start with a slash), so you probably want to omit the slash:

# ....
% {$_.replace("remotes","")}

Another way would be to replace /remotes and remotes by using -replace with a regex:

# ....
% {$_ -replace '\/?remotes'}

I would also consider to even use \b\/?remotes to ensure you don't replace remotes inside the string.

Upvotes: 3

Related Questions