0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

正規表現を使用してフォルダパスの一部を変更しファイルを移動させる

Last updated at Posted at 2019-06-08

正規表現を使ってフォルダパスの一部を変更&ファイルて移動させるVBscriptです。
(1個毎にファイルを移動しています)

前 ~/A/B/~
後 ~/B/A/~

前 c:\x\x\x\x\X-1\1111\x\x\x\a.txt
後 c:\x\x\x\x\1111\X-1\x\x\x\a.txt

この場合の正規表現はこちら。

(.*)\\(x-[0123456789])\\(\d{4})\\(.*)

仕様
・フォルダを最下層まで下ってファイルのフルパスを取得
・フルパスを正規表現を使用して
   \変更しない構成1\変更する構成1\変更する構成2\変更しな構成2
 に切り分ける
・移動先のファイルパスを組み立てる
・移動先のフォルダがない場合は該当フォルダを作成する
・移動元から移動先へファイル移動する

----以下コード----

Set fs = CreateObject("Scripting.FileSystemObject")
set re = createObject("VBScript.RegExp")

msgbox "START"

TARGET = "C:\tmp\hig\abc"  '--- 変更するフォルダのトップを指定 ---
KAKUNIN = 10   '---ここを1にすると移動を実行します。1以外は変更内容を確認です---
LIST = ""

'--- 条件 ---
re.pattern = "(.*)\\(x-[0123456789])\\(\d{4})\\(.*)"
re.ignoreCase = true
re.global = true

'--- 実行 ---
FindFolder fs.GetFolder(TARGET)

if KAKUNIN <> 1 then msgbox LIST,,"移動前後のファイル表示": end if

'--- END ---
Set re = Nothing
Set fs = Nothing

msgbox "END-END"


'--- 再帰呼び出フォルダ&ファイル取得 ---
Sub FindFolder(ByVal z)
        
    '--- 再帰的にフォルダ取得 ---
    For Each x In z.SubFolders
        FindFolder x
    Next
    
    '--- ファイル処理 ---
    For Each x In z.files
        
        '--- 条件にマッチしたらアクション ---
        set m = re.execute(x)
        if m.count > 0 then
        
          set mm = m(0).submatches    

          '--- ここでフォルダ構成を逆転 ---
          Fpath_mae = mm(0) & "\" & mm(1) & "\" & mm(2) & "\" & mm(3)
          Fpath_ato = mm(0) & "\" & mm(2) & "\" & mm(1) & "\" & mm(3)
          
          if KAKUNIN <> 1 then
          
            LIST = LIST & "--------" & vbcrlf & _
                     "前" & Fpath_mae & vbcrlf &  _
                     "後" & Fpath_ato & vbcrlf & vbcrlf 
          
          else
            '--- 移動先のパスがなければ再帰的にフォルダ作成する ---
            CreateFolderEx fs.GetParentFolderName(Fpath_ato)
            
            '--- 移動を実行 ---
            fs.movefile Fpath_mae, Fpath_ato
          end if
        end if
    Next
End Sub



'--- フォルダを再帰的に作成する ---
Sub CreateFolderEx(ByVal strPath)
    Dim strParent   ' 親フォルダ

    strParent = fs.GetParentFolderName(strPath)
    If fs.FolderExists(strParent) = True Then
        If fs.FolderExists(strPath) <> True Then
            fs.CreateFolder strPath
        End If
    Else
        CreateFolderEx strParent
        fs.CreateFolder strPath
    End If
End Sub
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?