Search code examples
command-linerenamefilenamesbatch-rename

Batch add basename to another file


I screwed up with mmv and deleted a few characters from the end of the filenames in a folder (before the extension).

Luckily I have other files with the same original basename but with a different extension. I would like to know whether there is a way make a loop:

  • To match the remainder of the basename from the modified file to the second file with the original filename.
  • If it matches, rename the file with the original filename

Example:

Wrong filenames: foo-1234.txt 
                 foo-1225.txt
Right files:    foo-1234-5678.png
                foo-1225-6789.png

Desired output:

foo-1234-5678.txt
foo-1225-6789.txt

Thank you very much in advance!


Solution

  • You didn't mention what environment we are talking about, but I'm assuming it's Windows cmd. You can try this:

      @echo off
      setlocal enabledelayedexpansion
      for %%f in (foo-*.png) do set f=%%f & rename !f:~0,8!.txt !f:~0,13!.txt
    

    It must be executed from batch file - delayed expansion won't work from direct command line.

    EDIT

    powershell counterpart:

    dir foo-*.png | % { $stem = $_.name -replace 'foo-([^.]+).png','$1'; $bad = $stem.substring(0,4); mv foo-$bad.txt foo-$stem.txt; }
    

    bash:

    for file in foo-*.png; do stem=${file:4:9}; bad=${file:4:4}; mv foo-${bad}.txt foo-${stem}.txt; done