You can use the regex-based -replace
operator as follows:
PS> ' |2080| | | | | | | | | | | | | |2000225| ' -replace ' (\||$)', '$1'
|2080||||||||||||||2000225|
This assumes that no non-empty fields have trailing spaces - if they do, their (last) trailing space will be removed; to avoid this, use the appropriate solution from Wiktor Stribiżew's helpful answer.
Regex (\||$)
matches a single space char. followed by either a literal |
(escaped as \|
) or (|
) the end of the string ($
); $1
in the replacement string then replaces whatever the 1st capture group ((...)
) matched; that is, if the space char. was followed by literal |
, it is effectively replaced with just |
; if it was followed by the end of the string, it is effectively removed.
A slight simplification is to use a positive lookahead assertion ((?=...)
), as also used in Wiktor's answer, which captures the space character only, and therefore allows omission of the substitution-text -replace
operand, which defaults to the empty string and therefore effectively removes the spaces:
PS> ' |2080| | | | | | | | | | | | | |2000225| ' -replace ' (?=\||$)'
|2080||||||||||||||2000225|