0

How can I Remove variable string in all filenames until first occurrence of the hyphen in PowerShell?

I have a list of files in the same folder like:

picture_1_2017-01-02_abc.jpg
picture_10_2017-01-03_dfc.jpg
picture_111_2017-01-04_sdfc.jpg
picture_20_2017-01-05_gh.jpg
picture_354_2017-01-06_asfd.jpg
...

I'd like to replace everything until first "hyphen" by "2017". For example, to replace "picture_10_2017" by "2017" and leave the rest of the name as is to receive the next list of files:

2017-01-02_abc.jpg
2017-01-03_dfc.jpg
2017-01-04_sdfc.jpg
2017-01-05_gh.jpg
2017-01-06_asfd.jpg

How can I do that in windows by PowerShell or any other tool?

grawity
  • 501,077

1 Answers1

1

From this earlier question, the overall structure for mass-renaming files is:

Get-ChildItem <glob> | foreach { Rename-Item $_ <newname> }

Each item has its original name stored in $_.Name, and when the regular fixed-string .Replace() method is not enough, use regular expressions.

Within PowerShell, you can access regex-based Replace() in two ways:

  • [regex]::Replace($str, $regex, $replacement)
  • $str -replace $regex, $replacement

To just remove the prefix

The regex ^picture_\d+_ will match the unwanted prefix; replace it with nothing.

After combining the two:

Get-ChildItem *.jpg | % { Rename-Item $_ ([regex]::Replace($_.Name, "^picture_\d+_", "")) }

Get-ChildItem *.jpg | % { Rename-Item $_ ($_.Name -replace "^picture_\d+_", "") }

Alternatively, to match the question, ^[^-]*- will match everything up to (and including) the first dash; replace it with "2017-" (assuming all files are from the same year – otherwise you might accidentally lose information).

To replace with part of the original

You can match part of the original text using ( ) and use it as the replacement using $1 ($2, $3...) This will give the same final result in your case, but more closely matches what you originally asked.

For example, regex "^picture_\d+_(\d+)-" and replacement '$1-' (must be single-quoted).

grawity
  • 501,077