Search code examples
windowscmdsubstring

Using CMD on Windows to remove a specific substring from a directory of files


I frequently use a free online lossless file compressor to save space on my disk and make transferring and pushing repos easier. My main problem with the compressor is it appends "-min" to the end of every filename. For various reasons, I want to replace the original files by overwriting them; instead of deleting the old files and keeping the new files (with the "new" names).

For my PDF directory, I tried this: FOR /R %f IN (*-min.pdf) DO REN "%f" *.pdf

And it seems to correctly find all the corresponding files, but their names remain the same. What am I doing incorrectly? Is there a single command that would be file-format-agnostic, so I wouldn't have to sub out the file extension for txt's, png's, etc?

I just need it to remove the -min from the end of each filename (before the file extension).


Solution

  • FOR /R %f IN (*-min.pdf) DO REN "%f" *.pdf

    For a one liner (at the cmd prompt) remove echo from the following.

    cmd /v:on /c "for /R %f in (*-min.pdf) do @set "nx=%~nxf" & echo ren "%~ff" "!nx:-min.pdf=.pdf!""
    

    The above can be easily changed to perform other string manipulations, but it is not technically foolproof, for example it will rename a file named "a-min.pdf.b-min.pdf-c-min.pdf" to "a.pdf.b.pdf-c.pdf.". If that is a concern in this case, then use the following, which is essentially the same as in @Mofi's answer.

    cmd /v:on /c "for /R %f in (*-min.pdf) do @set "nn=%~nf" & echo ren "%~ff" "!nn:~0,-4!%~xf""