Removing the SPACE before the second occurring of underscore "_"

Hi there:

Trust that you’re all in high spirits!

I’ve a peculiar question, how to remove the SPACE before the second occurring of underscore “_” using powershell.

For example:

234234_FULL NAME _Type_YEAR.pdf

shall be renamed to

234234_FULL NAME_Type_YEAR.pdf

 

Please note: the FULL NAME can contain any number of spaces, such as

2323242_JAMES BLUNT J _joining_2019.pdf

shall be

2323242_JAMES BLUNT J_joining_2019.pdf

Please advise!

Highly appreciated!

Cheers,

I assume that this is your first try to ask this question and your post got on hold, right? :wink:

Removing the SPACE before the second occurring of underscore “_”

I would probably split on the underscore, then take the -2nd (negative two) of the array. It might be negative three… anyway. I’d run the Trim() in the string. Then you can use a join operation with the underscore to bring it all back together.

 

Typing on my phone here so I’ll probably have to come back and fix this comment later. But here’s what it might look like.

$SplitArray = $myString -Split ‘_’

$SplitArray[-2].Trim()

$JoinedAgainString = $SplitArray -Join ‘_’

Closing this thread as it is continued here: https://powershell.org/forums/topic/removing-the-space-before-the-second-occurring-of-underscore-_-2/