LoginSignup
0
1

More than 5 years have passed since last update.

ファイル名に含まれる文字列でファイルを分類する with バッチ

Last updated at Posted at 2016-12-24

【概要】

ファイル名にある特定の文字列を含むファイルをそれぞれディレクトリにコピーします。

今回はファイル名に「1」と「3」を含むファイルを分類しました。

【プログラム】

ファイル分類.bat
@echo off

REM 遅延変数用
setlocal enabledelayedexpansion

REM ファイル名に含まれる対象文字
set targetName1=1
set targetName2=3

REM フォルダが既に存在する場合は削除する
for %%i in (%targetName1% %targetName2%) do (
  if exist %%i (
    rd /s /q %%i
  )
)

REM カレントディレクトリの中の全てのファイルについて分類する
for /r ./ %%i in (*) do (
  set fileDir=%%~dpi
  set file=%%~nxi
  if not "!file:%targetName1%=!" == "!file!" (
    call :copyFile !fileDir! !file! %targetName1%
  ) else if not "!file:%targetName2%=!" == "!file!" (
    call :copyFile !fileDir! !file! %targetName2%
  )
)
exit /b

REM ファイルをコピーする関数
:copyFile
set fileDir=%1
set file=%2
set targetName=%3
REM フォルダが既にあるかどうか
if exist %targetName% (
  REM ファイルが既にあるかどうか
  if exist !targetName!/!file! (
    cp !fileDir!!file! !targetName!/copy_!file!
  ) else (
    cp !fileDir!!file! !targetName!/!file!
  )
) else (
  md !targetName!
  cp !fileDir!!file! !targetName!/!file!
)
exit /b

【実行結果】

実行前
実行前.png

実行後
実行後.png

圧縮しようとしたが、バッチではzip形式で圧縮できないみたい・・・。
どうにかしてください!Microsoftさん!

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1