LoginSignup
4
0

More than 3 years have passed since last update.

バッチファイルでの配列

Posted at

はじめに

Windowsのコマンドプロンプトで用いるバッチファイルを書くことがそこまでなかったのですが、たまたま調べていたところ配列の扱い(疑似的)が可能ということでメモ。
殴り書きみたいなものなので、その程度と思っていただけると◎。

大前提

エコーの無効化と遅延環境変数の有効化を利用しています。

@echo off
setlocal enabledelayedexpansion

ファイルから読込して代入

同じディレクトリにあるlist.txtのn行目をarr[n]に代入したいとき。

set n=1
for /f %%s in (list.txt) do (
  set arr[!n!]=%%s
  set /a n=n+1
)

Foreachを使いたいとき

Foreachが何なのかみたいな説明はここでは省略しますが、とにかくForeachを使いたいとき。

rem Foreach Loop
set i=1
:FOREACH_FILEPATH
set it=!filepath[%i%]!
if defined it (
  set FullPath=%PathFrom%%it%
  set /a i+=1
  goto :FOREACH_FILEPATH
)

合わせ技の例

ファイルからlistを読み込んで、そこのファイル名からごにょごにょしたいみたいな例。

@echo off
setlocal enabledelayedexpansion

set PathFrom=C:\Users\test\Desktop\

rem filepath[n] <- list[n]
set n=1
for /f %%s in (list.txt) do (
  set filepath[!n!]=%%s
  set /a n=n+1
)

rem Foreach Loop
set i=1
:FOREACH_FILEPATH
set it=!filepath[%i%]!
if defined it (
  set FullPath=%PathFrom%%it%
  set /a i+=1
  goto :FOREACH_FILEPATH
)

参考

バッチファイルで配列を使う
バッチファイルで配列とforeachを使う方法

4
0
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
4
0