简体   繁体   中英

Batch file for creating folders based on filenames, and moving files

I got a bunch of pictures taken with my camera in a parent folder. The filenames has this format; 'yyyymmdd_ttmmss.jpg', eg '20151008_0730.jpg'. I want to create folders based on the 'yyyymmd'-part of the filename, but with the format 'yyyy-mm-dd'. So the file '20151008_0730.jpg' is moved into a folder named '2015-10-08'. This is what I got so far:

@ECHO OFF
SETLOCAL
SET "sourcedir=c:\temp"
PUSHD %sourcedir%
FOR /f "tokens=1*" %%a IN (
 'dir /b /a-d "*_*.jpg"'
 ) DO (  
 MD %%a
 MOVE "%%a %%b" .\%%a\
)
POPD
GOTO :EOF

But I don't know how to format the %%a-variable before creating the folder.

(This is a similar question asked before, but not with creating the folder on this format)

@echo off
setlocal

copy nul "%tmp%\20151008_0730.jpg"
copy nul "%tmp%\20151009_0731.jpg"
copy nul "%tmp%\20151010_0732.jpg"

set "sourcedir=%tmp%"
pushd %tmp%
for /f "delims=" %%a in ('dir /b /a-d "*_*.jpg"') do (
  set "file=%%a"
  setlocal enabledelayedexpansion
  set "folder=!file:~0,4!-!file:~4,2!-!file:~6,2!"
  echo:
  rem check if folder already exist
  if not exist "!folder!\nul" echo md "!folder!"
  echo move "!file!" "!folder!"
  endlocal
)
popd
exit /b 0

output:

md "2015-10-08"
move "20151008_0730.jpg" "2015-10-08"

md "2015-10-09"
move "20151009_0731.jpg" "2015-10-09"

md "2015-10-10"
move "20151010_0732.jpg" "2015-10-10"

You have to clean up this sample by changing sourcedir and pushd, removing echo in front of each commands, also copy nul "....".

I used here VarSubstring and delayedexpansion

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM