Skip to content

Instantly share code, notes, and snippets.

@cabrel
Last active December 21, 2015 18:39
Show Gist options
  • Save cabrel/6348490 to your computer and use it in GitHub Desktop.
Save cabrel/6348490 to your computer and use it in GitHub Desktop.
prefix directory name to each file
'
' Usage: `cscript prefix.vbs C:\path\to\folder\root`
'
Dim folderList, fileList, rootPath
rootPath = WScript.Arguments.Item(0)
folderList = Split(ShowFolderList(rootPath), ",")
For i = 0 to UBound(folderList)
RenameFiles folderList(i)
Next
'
' ShowFolderList("C:\Path")
'
Function ShowFolderList(path)
Dim fso, folder, subFlds, fld, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(path)
Set subFlds = folder.SubFolders
s = ""
For Each fld in subFlds
s = s & path & "\" & fld.name
s = s & ","
Next
' remove the trailing comma
s = Left(s, Len(s) - 1)
ShowFolderList = s
End Function
'
' ShowFileList("C:\Path")
'
Sub RenameFiles(path)
Dim fso, folder, files, subFolders, oldFilePath, newFilePath, alreadyModified
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(path)
Set subFolders = folder.SubFolders
For Each subFolder in subFolders
Set files = subFolder.Files
For Each file in files
oldFilePath = path & "\" & subFolder.name & "\" & file.name
newFilePath = path & "\" & subFolder.name & "\" & folder.name & file.name
alreadyModified = Left(file.name, Len(folder.name))
' To avoid prepending the folder name AGAIN, check to see if
' the prefix is already there
'
' This could break with legitimate folder names having the folder
' prefix
If alreadyModified <> folder.name Then
fso.MoveFile oldFilePath, newFilePath
Wscript.Echo "Moved '" & oldFilePath & "' to '" & newFilePath & "'"
Else
Wscript.Echo "It appears '" & oldFilePath & "' has already been renamed"
End If
Next
Next
End Sub
@cabrel
Copy link
Author

cabrel commented Aug 27, 2013

The path in the usage comment 'C:\path\to\folder\root' is expecting a structure like:

C:\path\to\folder\root:

1\
  1000\
  ...
2\
  2000\
  ...
3\
  3000\
  ...
...
n\
  n000\
  ...

Then the script will take the directory name and prepend it to each file name. For example:

1\
  1000\
    a_file.txt
    b_file.txt
    c_file.txt

The 3 files will be renamed and become:

1\
  1000\
    1a_file.txt
    1b_file.txt
    1c_file.txt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment