How to Rename Bulk Files using CMD - cmd

I have a bunch of sql files that I would like to rename as they have the schema name at the start of the file like the following:
SCHEMA.TABLE.sql
Which I want to be renamed to:
TABLE.sql
Unfortunately as I am trying to do this on my work laptop, I can't download any third party software such Bulk Rename Utility so I am trying to do this using CMD.
What I attempted was the following:
REN SCHEMA.*.sql *.sql
which looks like it finds a match but nothing changes. So not sure what I need to change so would appreciate any advice as to where I am going wrong.

The ren command interprets the * in the target pattern *.sql so that it matches all source characters up to the last ., meaning that it matches the portion SCHEMA.TABLE of your sample. Therefore, the target name equals the source name.
Consult this great post on Super User: How does the Windows RENAME command interpret wildcards?
To remove the SCHEMA. part from your file names you need to use a for /F loop:
for /F "eol=| tokens=1* delims=." %I in ('dir /B /A:-D-H-S "*.*.sql"') do ren "%I.%J" "%J"
This fails in case there are more than one ., like in SCHEMA..TABLE.sql, for example.
Do not forget to double the %-signs when you want to use that code in a batch-file!

1.This can be done using powershell script pretty easily. Copy following script, edit $path to the path where the files are located.
$path = 'D:\MyFolder\My docs\testdelete'
$pathObject = get-childitem -path $path | where-object {$_.Psiscontainer -eq $false}
foreach($file in $pathObject)
{
$fileNameArray = $file.Name.Split(".")
Rename-Item -Path $file.FullName -NewName ($fileNameArray[1]+".sql")
}
2.Next save this script in a file named, say testrename.ps1. Open cmd change directory to the location where you saved testren.ps1 file and further run following command:
powershell -file "testren.ps1"
Here $path is the path where the files are located. $pathObject will get all the files in the said location. Further we iterate each file, split the name to get what comes after 'schema' and further rename it. If cmd is not a restriction then 1st script can also be directly run by opening powershell window on windows, copy paste the script after modifying the path and hit Enter key. In this case step 2 is not required.

Related

Batch Renaming part of a file name in docs command line using REN

Trying to figure out how to batch rename part of a filename in doc command line using 'ren'.
My filenames:
abc_124_xyz_2021122345_123.txt
abc_124_xyz_2021122346_124.txt
abc_124_xyz_2021122347_125.txt
How do I get rid of the extra '2' (highlighted in bold above)
I tried using '?':
ren abc_124_xyz_20211?234?-???.txt abc_124_xyz_20211234?-???.txt
and
also tried using '*' in place of ???
neither worked.
For some reason underscore appears as a italicized ?. So I used hyphen.
See attached screenshot, which has underscore.
Ended up using powershell:
Get-ChildItem *.pdf | Rename-Item -NewName { $_.Name -replace '2021122', '202112' }
As far as I know windows is not able to do this smart kind of rename abc$1def$2ghi.txt to abcdef$2ghi.txt that you want (get rid of the first field).
Anyway, maybe a more generic single wildcard rename would work:
First, check if nothing more than expected is included:
dir abc_124_xyz_202112????????.txt
If it's ok, then run:
ren abc_124_xyz_202112????????.txt abc_124_xyz_20211????????.txt
If it is not ok, you can (1) move the files to an external folder to rename them in isolation or (2) build a renamer script that filter out the specific files and rename one by one, by a substring version that skips the 17th character:
Auxiliar folder approach:
md rentemp
move abc_124_xyz_20211?234?_???.txt rentemp
ren rentemp\abc_124_xyz_202112????????.txt abc_124_xyz_20211????????.txt
move rentemp\* .
rd rentemp
Auxiliar script approach:
for %f in ("abc_124_xyz_20211?234?_???.txt") do (
set n=%f
echo ren %n% %n:~0,17%%n:~18% >> renamer.bat
)
Then run renamer.bat
We need the renamer.bat because if we rename the own file which is used in the loop, the loop itself breaks, so the script below does not work:
for %f in ("abc_124_xyz_20211?234?_???.txt") do (
set n=%f
ren %n% %n:~0,17%%n:~18%
)

Listing files and folders and outputting it as .csv

I'm trying to write a batch script to list all the folders, sub-folders and files inside a directory, and then output everything to a .csv-file. I have tried this using the tree command but I also need the "Creation date" and "Last modified" date to be included. The tree command doesn't seem to support that. Is there any other way to do it?
Example:
tree "C:\Windows" /A /F > "C:\Log.csv"
Use a PowerShell one liner:
Get-ChildItem -Recurse | Select-Object FullName,CreationTime,LastWriteTime|Export-Csv C:\log.csv -NotypeInformation
if necessary wrapped in a batch:
powershell -NoP -C "Get-ChildItem -Recurse | Select-Object FullName,CreationTime,LastWriteTime|Export-Csv C:\log.csv -NotypeInformation"
What about Dir /S *.*?
The /S stands for "go through the directory and all subdirectories".
Sorry. I missed the part where you needed the creation dates. Those ones can be achieved as mentioned in this post.

Copying a File to Multiple Subdirectories in Same Directory

Expanding upon this example: Copying a file to multiple folders in the same directory I want to copy an XML file to several different project directories under the same root folder, so I have tried this:
for /d %a in (C:\Root\Output\*\bin\x64\Release) do copy /y C:\Root\OtherProject\MyXml.xml %a\
Where the wildcard would be a different project name in my solution directory.
When I run this command, there is no error, but the XML is not copied, so my question is can you use wildcards like this in Windows command line or alternatively is there a better way to tackle this kind of operation from within command prompt?
Just split it:
FOR /D %1 IN (c:\root\output\*) DO (
COPY /Y c:\root\otherproject\myxml.xml %1\bin\x64\release
)
Obviously this works if all subdirectories of c:\root\output must be included (they have a bin\x64\release subdirectory.) If it's not true then you have to include an extra check:
FOR /D %1 IN (c:\root\output\*) DO (
IF EXIST "%1\bin\x64\release" (
COPY /Y c:\root\otherproject\myxml.xml "%1\bin\x64\release"
)
)
Of course you may feel this is to much code for such simple task, well then maybe it's time to switch to PowerShell, Get-ChildItem supports wildcards used the way you want:
Get-ChildItem c:\root\output\*\bin\x64\release `
| ForEach-Object -Process `
{ Copy-Item -Force c:\root\otherproject\myxml.xml $_ }
If you love short syntax:
gci c:\root\output\*\bin\x64\release | % { cp -Force c:\root\otherproject\myxml.xml $_ }

Batch renaming with forfiles, or potentially Powershell

I have an issue when trying to bulk rename files within folders using forfiles and Powershell. The issue I am having is I need to search for files with _T_ in them, so I use the search notation *_T_*.cr2 as they are all RAW files. In a given folder there will be 143 or so RAW files, 69 of them will have _T_ in their names and the rest don't. What I want to achieve is run a quick command that weeds out all files with _T_ in them and then adds an extra _ before the file.
So before: Ab01_T_gh.cr2 and after _Ab01_T_gh.cr2
My issue is that searching for the _T_ files causes the command to keep executing over and over and over, so the file eventually looks like _____________Ab01etc until it hits the Windows file name limit.
Here's what my forfiles command looks like:
forfiles /S /M *_T_*.cr2 /C "cmd /c rename #file _#file"
It works but it works a little too well.
I also tried Powershell with the same result.
Get-ChildItem -Filter "*_T_*.cr2" -Recurse | Rename-Item -NewName { "_" + $_.Name}
Perhaps there's a way I could split up the "find" and "rename" parts of the code? Any help would be greatly appreciated! I can't manually separate out the _T_ files as it would be very time intensive as each parent folder will sometimes have 75 subfolders with 143 RAW files in each.
This works fine:
#echo off
setlocal EnableDelayedExpansion
for %%a in (*_T_.cr2) do (
set z=%%a
set z=!z:~,1!
if not !z!==_ rename %%a _%%a
)
I had to drop forfiles since I could not work with the # variables (maybe with findstr).
I resorted to a simple for loop on the pattern, and only rename if not already starts by underscore.
Recursive version:
#echo off
setlocal EnableDelayedExpansion
for /R . %%a in (*_T_.cr2) do (
echo %%~na%%~xa
set z=%%~na
set z=!z:~,1!
if not !z!==_ rename %%a _%%~na%%~xa
)
Here's a PowerShell version based on your original code:
Get-ChildItem -Filter "*_T_*.cr2" -Recurse |
Where-Object { $_.Name.Substring(0,1) -ne '_' } |
Rename-Item -NewName $("_" + $_.Name)

.Bat file to copy txt files without changing extension?

I need to copy all .TXT files under a directory [subfolders included] and copy them to another directory [without subfolders] but I can't change the extension of the files after I copy them, for example to .OLD or .TXT.OLD. Is that possible to do it via .bat file? Is there any special tool to use instead?
Consider using powershell instead:
Get-ChildItem C:\path\to\root\dir -recurse | where {$_.extension -eq ".txt"} | % {Copy-Item $_.FullName -Destination C:\path\to\target\dir}
You just need to use the root part of the filename and then append your own extension in the rename. For example, to demonstrate that (you don't say you're having any issue with the logic of the actual process, just the extension manipulation, so that's what I'm addressing):
FOR %%I IN (*.txt) DO REN %%I %%~nI.txt.old
This will take all *.txt files in the current directory and rename them to the same root + extension .txt.old. There's a possible complication in that the resulting filename cannot already exist in a rename, so you may want to put it into a more complex loop such as:
FOR %%I IN (*.txt) DO (
[do other stuff here]
IF EXIST %%~nI.txt.old DEL %%~nI.txt.old
REN %%I %%~nI.txt.old
)
Try for /? at a command prompt and check out the last part of it for the syntax of filename/path substitution parameters

Resources