Batch rename files and move into subfolders (which must be created)

0

I have a folder full of files of the format "10389-2001.pdf", so first a five digit number, a hypthen, and then a four-digit number. I want to rename all of the so that the file itself only is called "2001.pdf", but that it is moved into a new subfolder "10389". Since this subfolder does not exist yet, it would need to be created.

I am open to suggestions of how to do this on the Windows Command line, the Powershell, or Cygwin.

user1769925

Posted 2017-08-31T14:42:01.823

Reputation: 113

Have you tried anything? In PowerShell, I think that you only need to use .Stubstring(0,"-") of the file's BaseName and .Substring(1,"-") of the file's Name to get going: Move-Item -Path $original_file.FullName -Destination "$($(Split-Path -Parent -Path $original_file.FullName)\$($original_file.BaseName.Substring(0,"-"))\$($original_file.Name.Substring(1,"-"))" – flolilo – 2017-08-31T14:45:29.253

2Hi, and welcome to SuperUser. We are not a "please write me a script" kind of service. If you share your research, we'll help you point out where things are not working correctly. The solution can be done in any of the mentioned tools you want to use. For Batch, you will want to look into the command FOR. – LPChip – 2017-08-31T14:50:08.860

Hi, thanks for your responses. I am completely incompetent with PowerShell, so I have not tried anything there. I am familiar with the FOR command on the command line to create a loop, but I was struggling with the string manipulations there. – user1769925 – 2017-08-31T14:54:00.863

Answers

1

A PowerShell script:

Get-ChildItem *-*.pdf|Foreach-object {
    $Dir, $File = $_.Name.Split('-')[0,1]
    if (!(Test-Path $Dir)){MD $Dir}
    $_| Move -Destination ("$Dir\$File") 
}

The batch:

@echo off
for /F "Tokens=1* delims=-" %%A in ('Dir /B "*-*.pdf"') do (
    If not exist ".\%%A" MD ".\%%A"
    Move "%%A-%%B" "%%A\%%B"
)

Tree before:

> tree /f .
Z:\
    10389-2001.pdf
    10815-2017.pdf

Tree after:

> tree /f .
Z:\
├───10389
│       2001.pdf
│
└───10815
        2017.pdf

LotPings

Posted 2017-08-31T14:42:01.823

Reputation: 6 150

-1

Easy with VBS. Copy the code to a file with extention '.vbs'

on Error Resume Next   
sFolder = "D:\test\"
dFolder = "D:\test1\"
Set oFSO = CreateObject("Scripting.FileSystemObject")

For Each oFile In oFSO.GetFolder(sFolder).Files
    NameParts = split(oFile.Name,"-")
    Set f = oFSO.CreateFolder(dFolder & NameParts(0))
    set fi = oFSO.GetFile(oFile)
    fi.Copy dFolder & NameParts(0) & "\" & NameParts(1)
Next

adjust source and destination folder. Don't forget "\" at the end. Destination folder must exist. Quick'n'dirty coded. Only ?????-????? files in sourceFolder.

Joe6pack

Posted 2017-08-31T14:42:01.823

Reputation: 187