Home > Software design >  Rename a sequence of files to a new sequence, keeping the suffix
Rename a sequence of files to a new sequence, keeping the suffix

Time:01-15

I need help to create a command in PowerShell to rename a sequence of files with this format:

001.jpg
001_1.jpg
002.jpg
002_1.jpg
003.jpg
003_1.jpg

into a new sequence that can start with a number such as 9612449, but keeping intact the suffixes, so new sequence would be:

9612449.jpg
9612449_1.jpg
9612450.jpg
9612450_1.jpg
9612451.jpg
9612451_1.jpg

CodePudding user response:

Assuming that 9612449 is an offset to be added to the existing numbers that make up the first _-separated token or all of the base file names:

# Simulate a set of input files.
$files = [System.IO.FileInfo[]] (
  '001.jpg',
  '001_1.jpg',
  '002.jpg',
  '002_1.jpg',
  '003.jpg',
  '003_1.jpg'
)

# The number to offset the existing numbers by.
$offset = 9612449 - 1

# Process each file and apply the offset.
$files | ForEach-Object {
  # Split the base name into the number and the suffix.
  $num, $suffix = $_.BaseName -split '(?=_)', 2
  # Construct and output the new name, with the offset applied.
  '{0}{1}{2}' -f ($offset   $num), $suffix, $_.Extension
}

The above yields the output shown in your question.


Applied to a real file-renaming operation, you'd do something like:

Get-ChildItem -LiteralPath . -Filter *.jpg | 
  Rename-Item -NewName { 
    $num, $suffix = $_.BaseName -split '(?=_)', 2
    '{0}{1}{2}' -f ($offset   $num), $suffix, $_.Extension
  } -WhatIf

Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf once you're sure the operation will do what you want.

CodePudding user response:

Thanks a lot @mklement0! I tested it last night and it worked wonderfully, except that for the first file, it added 1 to the first digit of the new file name. For all other files it worked fine. So, for the sequence: 001.jpg 001_1.jpg 002.jpg 002_2.jpg

with an $offset = 1000

I´ve got the following:

1001_1.jpg 1002.jpg 1002_2.jpg 2001.jpg

where the last file 2000.jpg is in reality the previous 1st file 001.jpg

However, I got to create an workaround by creating a dud 1st file (for instance, 000.jpg), and then the sequence works perfectly

  •  Tags:  
  • Related