Rename a file by replacing few characters using Batch script - batch-file

I'm new to batch scripting and need help here.
My file name along with path is
C:\test\My_Test_File_20201006.txt
and I want to rename it as
C:\test\My_File_20201006.txt
using batch script only. I cannot use PowerShell here.
#echo off
set Pattern="Test_File"
set Replace="File"
Rem accepts the filename as cmd line argument
set filename=%1
Rem Update filename
set targetfile=%filename:Pattern=Replace%
Rem Rename the file
Ren %filename% %targetfile%
Exit
Using the above code, My file is renamed as "File". Tried % around the Pattern & replace variables, but no luck. Not sure where I'm going wrong. Tried all possible solutions from the StackOverflow and other tutorials, but none helped.
Edit:
After the proposed solution, getting a syntax error. The code is as below:
#echo off
set "filename=%~nx1"
echo %filename%
echo "%~dp1"
echo "%~dp1%filename:statement_=%"
ren "%~dp1%filename%" "%~dp1%filename:Test_=%"
I call my script from cmd line as:
D:/Test> C:/script/rename.bat C:\test\My_Test_File_20201006.txt
The echo statement correctly prints filename, directory & filename with the directory. Facing issues in rename statement.
Output:
My_Test_File_20201006.txt
"C:\test\"
"C:\test\My_Test_File_20201006.txt"
The syntax of the command is incorrect.

Three things wrong here.
You cannot add the quotes as part of the variable's value. It will actually use them as part of the variable. set variables to have double quotes including the variable name. For instance instead of set Pattern="Test_File" rather do set "Pattern=Test_File"
You never used the variables you've set Replace and Pattern
You either need to enabledelayedexpansion or use call to do the replacement because of the multple % required.
#echo off
set "Pattern=Test_File"
set "Replace=File"
Rem accepts the filename as cmd line argument
set "filename=%~nx1"
Rem Update filename
setlocal enabledelayedexpansion
ren "%~dp1%filename%" "!filename:%Pattern%=%Replace%!"
Another method, seeing as you only replace Test_ in your example:
#echo off
set "filename=%~nx1"
ren "%~dp1%filename%" "%filename:Test_=%"
EDIT
Fixing your example as per the edit.
#echo off
set "filename=%~nx1"
echo %filename%
echo "%~dp1"
echo "%~dp1%filename:statement_=%"
ren "%~dp1%filename%" "%filename:Test_=%"

Related

How to parse and echo multiple file paths using batch

I created a batch file that will echo or print the path of a file. Apparently, I am unable to print the path when I send multiple files as parameters to the said batch file.
#echo off
setlocal ENABLEDELAYEDEXPANSION
set string=%1
set string=!string:\=%%5C!
#echo %string% > D:\Playground\test.txt
Any help would be much appreciated. If there's anything unclear please let me know. Thanks.
Note: I send files to the batch file using the procedure below:
Right Click File
Send to
Choose the menu item that I created in sendTo that will pass the file to batch file
I don't know if this info helps but I didn't want to leave it out of my question.
%* will catch each input string passed separated by whitespace, enabledelayedexpansion should be used as you do set inside of a code block (). We also enclose the variables, including variable name with double quotes:
#echo off
setlocal enabledelayedexpansion
for %%a in (%*) do (
set "string=%%~a"
set "string=!string:\=%%5C!"
echo !string! >> D:\Playground\test.txt
)
As you can see, you need to use the for loop to iterate each of the input strings i.e %1 %2 and %3 etc.
As a Side note You can also drag and drop files onto the batch file to get results.
EDIT
Added the quote removal as requested set "string=!string:"=!" but note that using the strings as paths without quoting them will cause an issue in future if the paths contains whitespace.
To pipe to file without newline:
#echo off
setlocal enabledelayedexpansion
for %%a in (%*) do (
set "string=%%~a"
set "string=!string:\=%%5C!"
echo|set /p="!string! " >> D:\Playground\test.txt
)

Batch File - Get filename from directory and save as variable

I am trying to read in a directory and get the filename from that directory.
I then want to save the filename as a variable and echo that filename out.
Here is the code I am using:
for /F %%a in ('dir C:\Users\username\Documents\Training\Pentaho\Outputs\BatchFileOutput\ *.csv') do set FileName=%%a
echo %FileName%
I am getting the following when command prompt runs:
"File not found
Directory"
Does anyone know how to resolve this or where I'm going wrong?
Thanks
Safer way of doing the same:
#echo off
setlocal
set "yourDir=C:\Users\username\Documents\Training\Pentaho\Outputs\BatchFileOutput\"
set "yourExt=*.csv"
pushd %yourDir%
for %%a in (%yourExt%) do echo %%a
popd
endlocal
Sets both: Your directory and the extension you are searching for, Changes the directory to the one previously setted possibly including a /drive change and then runs a loop over all files matching your extension and echo them out. To save only the last one you can use:
...do set fileName=%%a
echo %FileName%
Or to use them all within the loop you can use:
#echo off
Setlocal EnableDelayedExpansion
REM Other things done here
do (
REM Do stuff with %%a here
Set filename=%%a
echo !filename!
echo !filename:~0,6!
echo !filename:a=b!
)
If you just want to echo them, you can just go for echo %%a. If you want to do other things like string-substitution or substrings as described in the comments you need DelayedExpansion as shown above. There are a lot of questions on SO as well.
Note that you can get different "parts" of the path of your file. Have a look on this answer I always have a look on as well. Alternatively check the documentation for the for command typing for /? into the command-line.

How to tell a batch script where another script is?

I have a script that I can run in the command line to get me the version of software. It works perfectly in the command line. I type this in getversion "<full path>" and it gets me exactly what I need.
Now the catch is that I have to have the getversion.bat and a vbscript file both in the directory that I'm in for the command line. This is probably a dumb question but if I want to add this into a batch script where the version is set as a variable how would I do that?
right now I had it looking like this
#echo off
set version=getversion "<full path>"
echo %version%
pause>nul
The problem seems to be that the batch file doesn't know where to find getversion.bat or the vbscript referenced in that script. How can I tell the batch file where they are?
One way to accomplish this is to direct the output of your function to a file and then read this output back into a local variable using a SET /P command. This should do it:
SET TempFile="%Temp%\%RANDOM%.txt"
REM Direct output to a temp file.
CALL getversion "<full path>">%TempFile%
REM Read the output written to the temp file into a local variable.
SET /P Version=<%TempFile%
ECHO %Version%
REM Cleanup.
IF EXIST %TempFile% DEL %TempFile%
Alternately (and this way much "cleaner"), you can use a FOR command to run your function and store the output into a local variable:
FOR /F "usebackq tokens=* delims=" %%A IN (`CALL getversion "<full path>"`) DO SET Version=%%A
ECHO %Version%

Batch renaming last few characters of files

I'm trying to create a batch file that would rename a bunch of files in a folder. These files would have a naming of something like: blah(lol).txt. There will always be a four letters, followed by an open bracket, three letters, and finally a close bracket.
I want the batch file to remove the bracketed part of the name of the file, ie. rename the file without the bracketed part.
for %%i IN (*.txt) DO (set name=%%~ni
set name2=%name:~1,4%
ren %%i %name2%)
Why doesn't this work?
Magoo provided an explanation as to why your script failed, as well as a working script.
But in your case, there is no need for a script. A simple REN command is all that is needed:
ren "????(???).txt" "????.*"
#ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
FOR /f "tokens=1,2,3delims=()" %%a IN (
'dir /b /a-d "%sourcedir%\*(*).*" '
) DO ECHO REN "%sourcedir%\%%a(%%b)%%c" %%a%%b%%c
GOTO :EOF
The required REN commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO REN to REN to actually rename the files.
Within a block statement (a parenthesised series of statements), the entire block is parsed and then executed. Any %var% within the block will be replaced by that variable's value at the time the block is parsed - before the block is executed - the same thing applies to a FOR ... DO (block).
Hence, IF (something) else (somethingelse) will be executed using the values of %variables% at the time the IF is encountered.
Two common ways to overcome this are 1) to use setlocal enabledelayedexpansion and use !var! in place of %var% to access the changed value of var or 2) to call a subroutine to perform further processing using the changed values.
simple but works from the folder with the files to be renamed.
#echo off
title Rename Bat
echo This bat must be in the folder that
echo contains the files to be renamed.
:begin
echo Enter File Name
set /p old=
echo Enter New Name
set /p new=
ren "%old%" "%new%"
echo File Renamed
ping -n 3 127.0.0.1 >NUL
goto begin
a much simpler approach ... try a for loop that cycles through all files in your folder
I'm going to use lol as an example of three letter word inside brackets as stated in your question
#echo off
for %%a in (*) do (
rename "%%a" "%%a(lol).exe"
)
to use this batch file you have to place it in the folder containing the files you wanna rename

Directory Names in Batch

How can I store a directory name in a variable inside batch file??
set dirname=c:/some/folder
echo %dirname%
REM retrieve the last letter of the folder
REM and save it in another variable
set lastLetter=%dirname:~-1%
echo %lastLetter%
To return the directory where the batch file is stored use
%~dp0
%0 is the full path of the batch file,
set src= %~dp0
echo %src%
I've used this one when I expect certain files relative to my batch file.
Without more precisions it's difficult to help you...
Maybe you want the current directory?
set name=%CD%
echo %name%
Use the set command.
Example:
rem Assign the folder "C:\Folder1\Folder2" to the variable "MySavedFolder"
set MySavedFolder=C:\Folder1\Folder2
rem Run the program "MyProgram.exe" that is located in Folder2
%MySavedFolder%\MyProgram.exe
rem Run the program "My Second Program.exe" that is located in Folder 2 (note spaces in filename)
"%MySavedFolder%\My Second Program.exe"
rem Quotes are required to stop the spaces from being command-line delimiters, but the command interpreter (cmd.exe) will still substitute the value of the variable.
To remove the variable, assign nothing to the name:
set MySavedFolder=
Since you are inside a batch file, I suggest surrounding your variable usage with setlocal and endlocal at the end of the file; this makes your environment variables local to the batch file and doesn't pollute the global environment namespace.
To allow a script to determine its parent folder directory name:
#echo off
::setlocal enableextensions,enabledelayedexpansion
SET CDIR=%~p0
SET CDIR=%CDIR:\= %
FOR %%a IN (%CDIR%) DO (
SET CNAME=%%a
)
echo %CDIR%
echo %CNAME%
pause
Or, better yet:
#echo off
::setlocal enableextensions,enabledelayedexpansion
SET CDIR=%~p0
SET CDIR=%CDIR:~1,-1%
SET CDIR=%CDIR:\=,%
SET CDIR=%CDIR: =_%
FOR %%a IN (%CDIR%) DO SET "CNAME=%%a"
echo %CDIR%
SET CNAME=%CNAME:_= %
echo %CNAME%
pause

Resources