A
A
Alexander2018-11-14 17:05:45
cmd/bat
Alexander, 2018-11-14 17:05:45

How to correct CMD/BAT regex?

Greetings!
I need to scatter files into folders, name folders by file name. There is a command:
For %%a in (*.jpg) do md "%%~na"& move "%%~a" "%%~na"
please tell me how to make all files with type name: 20495BW_ .jpg 20495BW.jpg 20495BW_(2).jpg 20495BW_(3).jpg 20495BW_*******.jpg (any characters after the underscore) were moved to a single folder called 20495BW?
Thank you in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
res2001, 2018-11-14
@Losyahka

If you have a prefix (20495BW) of a fixed length (7 characters) in all your files, then you can use the substring selection construct. It is described in the help for the set /?
But, given that the file name is in the loop variable, this construction cannot be applied directly - you must first assign the value %%a to a regular variable:

@echo off
setlocal ENABLEDELAYEDEXPANSION
for %%a in (*.jpg) do (
  set "dirname=%%~na"
  set "dirname=!dirname:~,7!"
  md "!dirname!"& move "%%~a" "!dirname!\%%~nxa"
)

But if the number of characters before the underscore can be different, then the above method will not work. In this case, to split the name into parts (with the separator "_"), you need to use for / f:
@echo off
for %%a in (*_*.jpg) do (
  for /f "tokens=1 delims=_" %%b in ("%%~na") do  (md "%%b"& move "%%~a" "%%b\%%~nxa")
)

If necessary, you can specify several delimiter characters - write them one after the other in the delims parameter of the nested loop.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question