.bat renaming the file with the content inside the parentheses - windows

So, previously I was here because I wanted to rename my file based on something that I created, I ended up doing it and it was a simple thing, but now, I am with another thing that I think it's better, so I have this code:
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
chcp 65001
SET "sourcedir=C:\Users\leandro.batista\Desktop\SAMPLES RENAMER"
SET "destdir=C:\Users\leandro.batista\Desktop\SAMPLES RENAMER\BACKUP"
FOR /f "delims=()" %%a IN ('dir /b /a-d "%sourcedir%\*.pdf" ') DO (
REN "%%a" "%sourcedir%\*.pdf"
PAUSE
)
I tried to rename the file with what was inside the parentheses of the file name, for exemple :
Input:
File Name: blablabla(exampleIwantToExtract)
OutPut:
File Name: (exampleIwantToExtract)
When I run the bat it says that has a syntax error and I am not pretty sure why, I have an ideia tho, it might be the REN code, or better, it must be the REN code.

if you use delims, you should also use the right token (2 for your example filename(s). If you don't define it, it defaults to 1, which would give you blablabla)
But for renaming a file, you need also the full name. Best method is to use two nested forloops. The outer loop a plain for to get the (old) filename and an inner for /f loop to tokenize the filename to get the new name:
for %%a in ("%sourcedir%\*.pdf") do (
for /f "tokens=2 delims=()" %%b in ("%%~na") do (
ECHO move "%%~fa" "%destdir%\(%%b)%%~xa"
)
)
%%~fa gives you the full qualified file name (including drive and path)
%%~na gives you the name of the file only
%%~xa gives you the extension of the file (of course you could simply type .pdf instead,
but %%~xa gives you additional flexibility)
Note: ren doesn't support destination path. Therefore I used move instead.

Related

Batch file to read file names from CSV and rename files in a folder

I have a set of codes in a file, i want to rename the files in a folder with that code. Like first code for the first file then second code for the second file.
for /f "delims=" %%x in (code.csv) do call :rename "%%x"
pause
GOTO :EOF
:rename
REN "*.jpg" "a/%1.jpg"
This is what I have written but this is like running the first code for all the files and am getting a duplicate file name that exists or the file can not found error. Even though the files are being renames but it takes lots of time which I believe due to some unnecessary looping.
Any help to make it perfect will be appritiated
You need a way to read the directory and the csv in parallel. There is a trick to do that:
#ECHO OFF
setlocal enabledelayedexpansion
<code.csv (
for /f "delims=" %%x in ('dir /b *.jpg') do (
set "NewName="
set /p NewName=
if not defined NewName goto :eof
ECHO ren "%%x" "!NewName!"
)
)
NOTE: remove the ECHO command after verifying it does what you want to actually enable the ren command.
<code.csv ( ... ) provides one line after the other to the set /p within the for loop. Clear it before reading, so the NewName variable gets undefined, when there are no more names from the csv. Exit the for loop, when it is undefined (no more names).
The loop stops, when there are either no more files to be renamed or no more new names from the csv file.
See dir /? - especially the /o switch for how to sort the files (if needed) for names, dates or sizes.
Another possibility is to build an array of either the csv content or the files but I think that's an overkill for this task.

BATCH: Delete parts of filename using substring not working

I have several .csv files in one folder. They are saved automatically but with spaces and execution date and time (in seconds) with amount of containing lines.
So far I was not able to run my powershell script with files containing spaces. So I tried to rename filenames using batch. so far nothing is working fine. Either in cmd-line or with a batch file.
Trying to loop in folder to find .csv is working but defining a string and then substring parts of the file not.
for %%i in ('dir *.csv /b /s') do set string = %%~ni
set substr=!string:~20,25!
echo !substr!
I tried first to use % instead of ! but didn't worked as well. Tried to use pipes for the loop as well, didn't worked.
So far my output is just
!string:~20,25!
My output has to be just the "real" filename of the report without anything else before or after it.
For example, do with that path and filename
C:\Users\Username\CSV_Files\Reportoutput Report_2017 2018-01-09T07_10_33.1924R.csv
this
C:\Users\Username\CSV_Files\Report_2017.csv
When I'm able to extract just the filename without any spaces or leading chars like "Reportoutput" (which is always the same) or starting time of report or containing lines in the report I could use that string and combine it with the path where files are saved.
Any ideas? Why is my "substring" not working at all? Do I miss some action? Some code?
I'm using windows.
Based on the file name structure you've presented and looping in one folder, (the current directory), as stated and used in your example code:
#Echo Off
For %%A In ("* * *.csv"
) Do For /F "Tokens=2" %%B In ("%%~nA") Do Ren "%%~A" "%%B%%~xA"
If you wanted to check inside subfolders of the currect directory then change it to this:
#Echo Off
For /R %%A In ("* * *.csv"
) Do For /F "Tokens=2" %%B In ("%%~nA") Do Ren "%%~A" "%%B%%~xA"
…and if you want to specify the base directory name then you can do so like the following two examples which use %UserProfile% for demonstration purposes, (change as appropriate).
#Echo Off
For /R "%UserProfile%" %%A In ("* * *.csv"
) Do For /F "Tokens=2" %%B In ("%%~nA") Do Ren "%%~A" "%%B%%~xA"
and:
#Echo Off
CD /D "%UserProfile%" 2>Nul||Exit /B
For /R %%A In ("* * *.csv"
) Do For /F "Tokens=2" %%B In ("%%~nA") Do Ren "%%~A" "%%B%%~xA"
Instead of splitting the names using character numbers, this simply takes the second token of the file name string delimited by spaces and adds the original file extension to it in a rename command.

Nested FOR with variables

I'm attempting to write a batch script that will go through a list of computers, read a file from the computer, delim the file name, then echo the computer name and the file name result. The issue I'm having is getting the computer name variable to populate in the nested FOR /R command. Here is my script:
#ECHO OFF
SetLocal EnableDelayedExpansion
SET LIST=Computers.txt
FOR /F %%A IN (%LIST%) DO (
FOR /R \\%%A\c$\folder1\folder2 %%B IN (*.txt) DO (
FOR /F "tokens=2 delims=." %%C IN ("%%B") DO (ECHO %%A %%C
)
)
)
EndLocal
The filename is something like RB-C1SRC20160716CL.P17.txt. So the result I am looking for is
MyPCName P17
But I get a blank result. What I have found is that %%A var is being populated from the text file but the %%A var in the FOR /R is not populating. If I ECHO ON the FOR commands I'm seeing FOR /R \%a\folder1\folder2 instead of FOR /R \MyPCName\folder1\folder2. This breakdown is keeping the rest of the script from working properly.
The root directory of a for /R command cannot be given by another for variable (like %%I) nor a variable using delayed expansion (!VAR!), unfortunately. You need to specify it either iterally, by a normally expanded variable (%VAR%) or by an argument reference (%1, %2,...).
A good work-around is to place the for /R loop in a sub-routine and use call to call it from your main routine. The (variable holding the) root path needs to be passed as an argument to call. In the sub-routine it is referred to by an argument reference (like %1).
Take a look at this answer of the post "Get size of the sub folders only using batch command" to see how this can be accomplished.
Another option is to temporarily change into the root directory before the for /R loop, which then defaults to the current working directory. Use pushd"\\%%A\c$\folder1\folder2" to change to the target directory, then put popd behind the for /R loop to return to the former directory.

Trim Date from file name windows script

How do you trim the date from a text file. For example, I have multiple files like:
test_MX_abc_20091011.txt
test_MX_pqrdhdsu_20091011.txt
test_MX_xyieuz_20091011.txt
All files will have test_MX in common but the 3rd part will of different size.
I would like to change into:
test_MX_abc.txt
test_MX_pqrdhdsu.txt
test_MX_xyieuz.txt
I know how to change the file if name is like test_20091011.txt with the below code, But if name has more string along with date, how to do that?
for /F "tokens=1 delims=_" %%i in ("%%~na") do (
move /Y %%~fa %data_in%\%%i%%~xa >nul
)
Thanks in advance.
This rename operation can be done for example with:
#echo off
for /F "tokens=1-3* delims=_" %%A in ('dir /A-D /B test_MX_*.txt') do (
ren "%%A_%%B_%%C_%%D" "%%A_%%B_%%C.txt"
)
Each file name is separated into 4 strings assigned to loop variables A to D with using underscore as separator. The loop variable D takes everything of file name after third underscore.
Or also working for the 3 files:
#echo off
setlocal EnableDelayedExpansion
for /F "delims=" %%F in ('dir /A-D /B test_MX_*.txt') do (
set "ActFileName=%%~nF"
set "NewFileName=!ActFileName:~0,-9!"
ren "%%~F" "!NewFileName!.txt"
)
endlocal
This solution assigns the name of a file without file extension and path to environment variable ActFileName. Next a new environment variable with name NewFileName is defined with name of active file without the last 9 characters (underscore and date string). This modified file name is used next in the rename operation.
Other solutions using commands for, set and ren can be found on Stack Overflow.
Search with the string
[batch-file] for set rename files
and more than 600 results are presented all using more or less something like above.
For details on the used commands, open a command prompt window, execute one after the other following commands and read output help.
dir /?
for /?
ren /?
set /?

Windows batch file error passing variable (.bat)

I'm trying to loop recursively through all the files inside a folder.
I need to read the file name, abcd_somethingone_pqrs.csv is the file name pattern. I need to create a folder (if the folder does not exist) named somethingone and move the file into that folder. I have started writing the following code in a .bat.
FOR /R D:\MOE\MRs\batchfiles\01\ %%F in (*.*) do (
echo %%~nF
set newloc=%%~nF
echo %newloc%
)
The line1 prints the filenames in the folder correctly. But when I read it to the new variable newloc, always the line4 prints only the last file's name. Can anyone please realize what's going wrong here or propose me a method to do this.
EDIT: Totally changed my answer and actually attempted to completely solve your overall problem instead of just the thing you were stuck on.
You'll have to update target_dir to wherever you want the files to go.
#echo off
setlocal enabledelayedexpansion
set source_dir=D:\MOE\MRs\batchfiles\01\
set target_dir=D:\something\
:: Recursively search the source directory for files
for %%A in (somethingone somethingtwo somethingthree) do (
for /F "delims=" %%B in ('dir /a:-d /s /b %source_dir%*%%A*') do (
REM if the directory does not exist, make it
if not exist %target_dir%%%A mkdir %target_dir%%%A
move %%B %target_dir%%%A
)
)
You need to enable delayed expansion so that the variable value inside the for loop will propagate correctly.
setlocal enabledelayedexpansion
for /R D:\MOE\MRs\batchfiles\01\ %%F in (*.*) do (
echo %%~nF
set newloc=%%~nF
echo !newloc!
)

Resources