Вопрос

I want to rename files using the command prompt with a prefix of 'g_x_'. The structure of the original file names are:

000_1565.7k

I have tried:

ren *.7k g_x_*.7k

That code will rename the files to 'g_x_1565.7k', but i really need the files to be named 'g_x_000_1565.7k'

Any ideas on why the code is dropping part of the original file name?

Thanks,

DH

Это было полезно?

Решение

@ECHO OFF
SETLOCAL
FOR /f "delims=" %%a IN (
  'dir /b /a-d *_*.7k ^|findstr /v /b /l "g_x_" '
 ) DO (
  REN "%%a" "g_x_%%a"   
)
GOTO :EOF

The dir finds filenames that match *_*.7k and this is piped to a FINDSTR which allows through only those names that do NOT match (/v) the literal (/l) string "g_x_" at the beginning (/b). The caret (^) before the pipe is required to tell CMD that the pipe is part of the command to be executed by the for, not a parameter to the dir.

The resultant filenames are then assigned to %%a, prepended and renamed

This approach first makes a list of the existing filenames, then processes that list. If an attempt is made to rename in-place, then it's possible that a file aaa_bbb.7k would be renamed to g_x_aaa_bbb.7k and then again to g_x_g_x_aaa_bbb.7k...

Другие советы

Store the filename of each file in a variable and prefix it with 'g_x_' + variable name.

If all your files begin with 000_* then use the following on the command line:

FOR %? IN (000_*.7k) DO ren %? g_x_%?

in the batch file, use:

FOR %%? IN (000_*.7k) DO ren %? g_x_%%?

This is a modified version of @PeterWright solution but it allows you to add /s in the DIR switches to process subdirectories too, if you need to do that.

As it stands it will only echo the rename commands to the screen - so remove the echo to enable the rename if you like what you see on the screen.

@ECHO OFF
FOR /f "delims=" %%a IN (' dir /b /a-d *_*.7k ') DO (
 echo REN "%%a" "g_x_%%~nxa"   
)
pause
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top