user770022
user770022

Reputation: 2959

File rename key off the first underscore to the next period

How can I filter on the first underscore and the following period

Here is what I have so far but the file I'm receiving is changing, in some cases the original filename has an extra underscore. I need a way to account for that.

Get-ChildItem "\\MyFileServer\*" | Rename-Item -NewName { ($_.Name -replace '(?<=^.{3}).{5}', '.').Replace(".vfmpclmadj.", ".sa.") } 

original filename

999_987895_888888_544P.44444.vfmpclmadj.000025001.20201216.175314

New filename

999.44444.sa.000025001.20201216.175314

Upvotes: 0

Views: 129

Answers (1)

Doug Maurer
Doug Maurer

Reputation: 8868

Something like this should work.

('999_987895_888888_544P.44444.vfmpclmadj.000025001.20201216.175314' -replace '_.+?(?=\.)').Replace(".vfmpclmadj.", ".sa.")

It simply looks for an underscore plus any characters up to a period. You could make it more strict but for this example it wasn't needed. Something like this would also work but only on the first underscore. The former could potentially affect other underscores later in the string.

('999_987895_888888_544P.44444.vfmpclmadj.000025001.20201216.175314' -replace '(?<=^[^_]+)_.+?(?=\.)').Replace(".vfmpclmadj.", ".sa.")

Upvotes: 1

Related Questions