Home > Blockchain >  How to replace the last unknow part of a file path using PowerShell
How to replace the last unknow part of a file path using PowerShell

Time:04-26

I have folder pathes like

\Street\House\Level\Room\321

or

\City\Street\House\Level\Room\1023

and want to replace the last digits (here: 321 or 1023) with another number (i.e. 567) using PowerShell 5.1.

However the path can vary like the last digits can do.

How can this replacement be done?

I assume using RegEx, but I got lost regarding this ...

CodePudding user response:

In your example a simple replace would do but assuming there could be numbers in other places in the string you can use a RegEx that captures one or more digits at the end of the string.

\d matches a digit (equivalent to [0-9])

matches the previous token between one and unlimited times

$ asserts position at the end of a line

[RegEx]::Replace('\Street\House\Level\Room\321', '\d $', '1023')
[RegEx]::Replace('\City\Street\House\Level\Room\1023', '\d $', '567')

Output:

\Street\House\Level\Room\1023
\City\Street\House\Level\Room\567
  • Related