Removing certain parts of a files name using cmd - batch-file

I've been attempting to remove a certain string from a bunch of files but I am unable to do it. The part I want to rename is the .english in my files. How would I do this?
https://i.stack.imgur.com/rhRKG.png

#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
rem The following setting for the source directory is a name
rem that I use for testing and deliberately includes spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.
SET "sourcedir=u:\your files"
FOR /f "delims=" %%b IN (
'dir /b /a-d "%sourcedir%\*.english.*" '
) DO (
SET "newname=%%b"
ECHO REN "%sourcedir%\%%b" "!newname:.english.=.!"
)
GOTO :EOF
Always verify against a test directory before applying to real data.
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.

Because your string splitting is at periods, ., I'd offer the following methodology.
In cmd.exe:
for %g in ("*.english.wav") do #for %h in ("%~ng") do #ren "%~g" "%~nh%~xg"
From a batch file:
#For %%G In ("*.english.wav") Do #For %%H In ("%%~nG") Do #Ren "%%~G" "%%~nH%%~xG"
As your question is unclear as to the intended final filename.
If you wanted to replace .english with something else, lets say .german, rather than simply removing it, then change:
"%~nH%~xG", or "%%~nH%%~xG"
To:
"%~nH.german%~xG", or "%%~nH.german%%~xG"

Related

Loop through folder with files including a space

I want to loop through a folder and let run an algorithm on each .tif file found. Unfortunately this does not work for files which have a space character in their name. As my path already contains folders with space, i put the variable which stores the path name in double-quotation marks.
FOR /F %%k IN ('DIR /B "%mypath_import%"*.tif') DO (
SET infile=%%k
SET outfile=!infile:.tif=_UTM.tif!
REM ... do something
This is my attempt so far but it won't work for the files which include a space as well.
You done need all that. You can use the normal for loop without having to use /f
#echo off
setlocal enabledelayedexpansion
set "mypath_import=C:\Some path"
for %%i in ("%mypath_import%*.tif") do (
set "infile=%%~i"
echo "!infile:.tif=UTM.tif!"
)
The above will however echo full path to and file name, if you want filename only with extension:
#echo off
setlocal enabledelayedexpansion
set "mypath_import=C:\Some path"
for %%i in ("%mypath_import%*.tif") do (
set "infile=%%~nxi"
echo "!infile:.tif=UTM.tif!"
)
or without the need to delayedexpansion
#echo off
set "mypath_import=C:\Some path"
for %%i in ("%mypath_import%*.tif") do echo %%~dpni_UTM%%~xi
and again if you require the name and extension only.
#echo off
set "mypath_import=C:\Some path"
for %%i in ("%mypath_import%*.tif") do echo %%~ni_UTM%%~xi
EDIT
As per comment from #Stephan, keep in mind if you are doing actual renames and you run the script more than once it will keep on appending _UTM each time. So you'll get filename_UTM_UTM.tif etc. So you can exclude files from the loop by including findstr
for /f "delims=" %%i in ('dir /b *.tif ^|findstr /eiv "_UTM.tif"') do echo %%~ni_UTM%%~xi

Batch: find files with specific content and extend existing name

I have about 100 .xml files, but its filenames are not self-explanatory. Therefore I would like to look for a specific word and extend the respecting file with this word.
Thanks to some other helpful entries, I could partially figure out how to do this, but somehow the files are not renamed.
Has anybody an idea what is wrong with my code? Thank you in advance.
chcp 1252
SET sourcedir=P:\path
FOR /f "tokens=1 delims=." %%a IN ('findstr /c:"3256" "%sourcedir%\*.xml"') DO (
ECHO (REN "%%a.xml" "%%a_3256.xml")
)
pause
chcp 1252
SET "sourcedir=P:\path"
FOR /f "delims=" %%a IN ('findstr /m /c:"3256" "%sourcedir%\*.xml"') DO (
ECHO REN "%%a" "%%~na_3256%%~xa"
)
pause
In your code you are using %%a for both arguments to ren command, but the second argument must only contain the name and extension, without path. You can solve it using %%~na, that is, the file name (without path or extension) of the file being referenced by %%a (%%~xa is the extension)
Also, if the string is found more than once in any file, your code will try to rename the file twice (or more). It is better to use the /m switch in findstr to only retrieve the list of files.
Rename operations are only echoed to console. If the output is right, remove the echo command.
Dang it MC ND, right after I did some frankenstein scripting, coming up with:
After trial and error along with this great website, I managed to come up with (giving credit to DOS Batch : remove characters from string in a FOR loop )
#ECHO OFF
set pathd=C:\SomePathHere
setlocal enabledelayedexpansion
for /f %%a in ('findstr /ic:SearchString %pathd%\*.xml') do (
set str=%%a
set str=!str:^:=!
echo !str!
)

I need to create a list of folders that contain a specific file type with a batch file

Using a batch file I'm trying to generate a list of only folders within a location that contain a certain file type, let's call it *.abc
at the moment I only know how to echo a DIR command output to a file called folder.lst, I would like to expand on that and try to either
a) echo only folders containing the *.abc file type to folder.lst
b) remove references in folder.lst of folders that do not contain the *.abc file type.
I also tried having a FOR loop check each line to see if a *.abc file existed in that location and skip it, if not, but I just could not get that to work, here is an example of what I had.
setlocal enableextensions enabledelayedexpansion
FOR /F "delims=" %%C in (folder.lst) do (
set temp=%%C
if not exist !temp!\*.abc (goto skip) else (goto resume)
:resume
then my actions live here
:skip
)
but I am aware I am doing something wrong here...I just do not know what.
Maybe the /R form of the for command will help:
for /r "basedir" %%a in (.) do if exist "%%~a\*.abc" (
echo %%a contains .abc file(s)
)
The %%a will be the directories you want (with a trailing \., but you should be able to not care or accommodate this).
There are problems with such of the script as you have posted in that you can'y use labels within a block statement. You've also not provided any examples.
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=U:\sourcedir"
SET "lastdir="
FOR /r "%sourcedir%" %%a IN (*.abc) DO IF "!lastdir!" neq "%%~dpa" (
SET "lastdir=%%~dpa"
ECHO %%~dpa
echo "!lastdir:~0,-1!"
)
GOTO :EOF
Each directory found will be echoed twice - one with the trailing \ and once without.
You would need to change the setting of sourcedir to suit your circumstances.
#echo off
setlocal enableextensions disabledelayedexpansion
set "root=%cd%"
for %%a in ("%root%") do for /f "delims=: tokens=2" %%b in ('
dir /a-d /s "%root%\*.abc" ^| find "\"
') do echo(%%~da%%~pnxb
This executes a recursive dir command searching for the indicated file type under the starting point (change root variable to suit your needs). For each found folder we retrieve the folder from the dir header that precedes the file list (the lines that contain a backslash).
To separate the path from the rest of the information in the line, the colon is used as delimiter. As this will leave the drive out of the retrieved information, an aditional for is used to retrieve the drive from the folder reference.
From the command line:
for /f "delims=" %a in ('dir /s /b *.abc') do echo %~dpa >> folders.lst
In a batch file:
for /f "delims=" %%a in ('dir /s /b *.abc') do echo %%~dpa >> folders.lst
The above commands will place only the folder names containing the *.abc files in folders.lst.
Notes:
% should be replaced by %% when the command is used in a batch file.
The ~dp part of %~dpa expands %a to a drive letter and path only. Remove the d if you don't want the drive letter. The p path includes a trailing \ which may be interpreted as an escape character by some commands.
The above commands start the search in the current directory. To search from the root of the current drive you can do cd \ first.
For more information see FOR /F Loop command: against the results of another command and Parameters.

Read the file names of all *.kla files in a directory, rename them and move them to a new directory by batch

I would like to read the name of all *.kla files from a directory (C:\TSData\Klarf) and change their names and then move them to a new directory (E:\MESSDAT\DATEN\Klatencor\Klarf).
For file name renaming, in each .kla file, there are two variables that i need to get their values: (for example)
LotID "N_123"; Slot 1;
and combine these variables like this: LotID_Slot.kla to make a new name.
I wrote this code but shows this error: "~nxi was unexpected at this time"
#echo off
setlocal enableDelayedExpansion
set "LotID="
set "Slot="
:: Finding the name of *.kla files in C:\TSData\Klarf\
for /f %%l in ('dir /b C:\TSData\Klarf\*.kla ') do (
echo %%l
:: Finding LotID, Slot in each .kla file
for /R C:\TSData\Klarf\ %%i in (*.*) do echo %%~nxi
for /f "usebackq tokens=1,*" %%a in (
"C:\TSData\Klarf\%%l"
) do for %%c in (%%b) do set "%%a=%%~c"
move /-y "C:\TSData\Klarf\%%l" "E:\MESSDAT\DATEN\Klatencor\Klarf"
ren E:\MESSDAT\DATEN\Klatencor\Klarf\%%l "%LotID%_%Slot%.kla"
)
Consider that in C:\TSData\Klarf\ there is a file name= 1.kla after execution of path file this file will be renamed to k1_1.kla (because for this file we have LotID=k1, Slot=1) and will move to new directory called E:\MESSDAT\DATEN\Klatencor\Klarf\ with its new name (k1_1.kla).
I dont know why this following For works well alone for a clear .kla file.
:: Finding LotID, Slot in each .kla file
for /R C:\TSData\Klarf\ %%i in (*.*) do echo %%~nxi
for /f "usebackq tokens=1,*" %%a in (
"C:\TSData\Klarf\K.kla"
) do for %%c in (%%b) do set "%%a=%%~c"
move /-y "C:\TSData\Klarf\k.kla" "E:\MESSDAT\DATEN\Klatencor\Klarf"
ren E:\MESSDAT\DATEN\Klatencor\Klarf\k.kla "%LotID%_%Slot%.kla"
Please kindly help me.
Thanks a lot!
#echo off
setlocal enableDelayedExpansion
set "LotID="
set "Slot="
:: Settings for OP's version
SET "sourcedir=C:\TSData\Klarf"
SET "destdir=E:\MESSDAT\DATEN\Klatencor\Klarf"
:: Overriding settings for Magoo's setup
SET "sourcedir=U:\TSData\Klarf"
SET "destdir=U:\destdir"
:: Finding the name of *.kla files in C:\TSData\Klarf\
for /f "delims=" %%l in ('dir /b "%sourcedir%\*.kla" ') do (
echo %%l
REM
REM NOTE USE OF REM NOT :: WITHIN A BLOCK (FOR..%%l)
REM
REM Finding LotID, Slot in each .kla file
REM
REM No idea why this line is here for /R "%sourcedir%" %%i in (*.*) do echo %%~nxi
REM
for /f "usebackq tokens=1,*" %%a in (
"%sourcedir%\%%l"
) do for %%c in (%%b) do set "%%a=%%~c"
REM
REM Note that MOVE across devices (C: to E: will COPY AFAIAA)
REM
ECHO(move /-y "%sourcedir%\%%l" "%destdir%\"
REM
REM Note use of !var! not %var% to access changed values LotID and Slot, not original values
REM
ECHO(ren "%destdir%\%%l" "!LotID!_!Slot!.kla"
ECHO(move /-y "%sourcedir%\%%l" "%destdir%\!LotID!_!Slot!.kla"
)
GOTO :EOF
You would need to change the setting of sourcedir and destdir to suit your circumstances. I've set them as I customarily do, and overridden the setting with values to suit my system.
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.
The required MOVE commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(MOVE to MOVE to actually move the files. Append >nul to suppress report messages (eg. 1 file moved)
As I commented, the :: comment should be replaced by rem comment within a block.
You haven't indicated how the new name is constructed. "LotID" and "Slot" seem to appear from nowhere. On analysing your code, it would appear that lines similar to
LotID is often k1
Slot might be 1
may appear in your .kla file. Your method of setting these variable may or may not be valid - without sample data, it's not possible to tell.
I believe that attempting to move files from one device to another will in fact copy the file, so the original file would stay in its original place and a copy would appear with the new name in the destination. I've aded an extra line to show how this could be done in a single line rather than two.
Here's the code I used to create a .kla file for testing, since you haven't provided sample data:
FOR %%a IN ("LotID perhaps is Z99"
"Slot is arguably 6") DO ECHO %%~a
)>"%sourcedir%\two.kla"
As for the reason for the for /r - heaven alone knows what this is meant to do!
Edit : to fix filenames with spaces...the for...%%l has the "delims=" option added.
Filenames tested include :
"%sourcedir%\1.kla"
"%sourcedir%\1 that is one.kla"
"%sourcedir%\t(w)o.kla"
"%sourcedir%\t(w, and a bit)o.kla"
"%sourcedir%\t(w,hree)o.kla"
Where sourcedir itself contained a space.
Please indicate file and directorynames failing if you find others...

Batch: Rename multiple files using input string

I am trying to rename files after the user inputs a string they want to remove from the file name. This works fine except when I want to rename files that are in a different location than the script:
Here is what i have so far which works if I dont specific the file path (e.g. remove C:\DATABASE\*.* /s)
SET /P X=Type in the String that you want to remove and then press ENTER:
set deletestring=%X%
for /f "delims==" %%F in ('dir C:\DATABASE\*.* /s /b ^| find "%deletestring%"') do (
set oldfilename=%%F
set newfilename=!oldfilename:%deletestring%=!
Ren "!oldfilename!" "!newfilename!"
)
Thanks!
Use this instead. e.g.:
remove *.*
or
remove "relative path\*.*"
or
remove C:\DATABASE\*.*
or
remove "C:\My Database\2010-*.bak"
Meaning that a directory and file mask must be specified. Here's the remove.bat file:
#echo off
setlocal enabledelayedexpansion
set mask=%~1
set mask=!mask:%~dp1=!
if not exist "%~1" (
echo No files found
goto :eof
)
pushd "%~dp1"
SET /P X=Type in the String that you want to remove and then press ENTER:
set deletestring=%X%
for /f "delims==" %%F in ('dir "%mask%" /s /b ^| find "%deletestring%"') do (
set oldfilename=%%F
set newfilename=!oldfilename:%deletestring%=!
Ren "!oldfilename!" "!newfilename!"
)
Your primary problem you are running into is that the 1st argument to REN can accept full path info, but the 2nd can only contain the new name without path info. You can use the ~nx modifier to extract the name and extension from the full path reported by the FOR /F command.
Your FOR /F options are not reliable - it will break if the file name contains =. You want to set delims to nothing instead.
This problem is actually more complicated than it first looks. Your code will attempt to rename both files and directories. If you want to rename the directories then you must rename in reverse alpha order because the entire list is built before any thing is renamed. If you process in normal alpha order and rename a directory, then subsequent entries within that directory will not be found.
The FIND filter in the IN() clause is not necessary. Ideally your filter should only match the file or directory name, not the path. That is doable, but a bit tricky. I would simply skip the filtering in the IN() clause and do it in the DO clause.
A file or directory name can contain ! character. But the FOR variable expansion will be corrupted if it contains ! and delayed expansion is enabled. The problem can be avoided by toggling delayed expansion on and off within the loop.
It is possible for the entire name to be removed by the search and replace, but you cannot rename a file to nothing. So I added a test to ensure there is a name left.
setlocal disableDelayedExpansion
SET /P "X=Type in the String that you want to remove and then press ENTER:"
for /f "delims=" %%F in ('dir C:\DATABASE\* /s /b ^| sort /r') do (
set "old=%%F"
set "file=%%~nxF"
setlocal enableDelayedExpansion
set "new=!file:%X%=!"
if defined new if !new! neq !file! ren "!old!" "!new!"
endlocal
)
If you don't really want to rename directories then you need to add the /A-D option. I first thought you could use a FOR /R statement, but that could potentially cause the same file to be renamed twice. FOR /F buffers the entire result set before processing any files, but FOR /R does not.
setlocal disableDelayedExpansion
SET /P "X=Type in the String that you want to remove and then press ENTER:"
for /f "delims=" %%F in ('dir C:\DATABASE\* /s /b /a-d') do (
set "old=%%F"
set "file=%%~nxF"
setlocal enableDelayedExpansion
set "new=!file:%X%=!"
if defined new if !new! neq !file! ren "!old!" "!new!"
endlocal
)

Resources