How to remove digits from beginning of filename? - batch-file

I need to rename a filename like this 7612372 filename 50x50.jpg into this filename 50x50.jpg, removing all digits at the beginning of the filename.
The number of digit can be variable.
I need to integrate this into an existing batch file run from the Windows command prompt.

If the format of the filename would be the same for all the files in the folder, then you can try:
#echo off
for /F "delims=" %%A IN ('dir /b /A-D') do (
for /F "tokens=2-3" %%B IN ("%%A") do (
ren "%%~fA" "%%B %%C"
)
)
This is the shortest way, but not the most accurate one. It is unsecure, because if the filename contains spaces, the file will be rename incorrectly. I suggest the following code for the task:
#echo off
setlocal EnableDelayedExpansion
for /F "delims=" %%A IN ('dir /b /A-D') do (
set filename=%%A
for /F "tokens=1" %%B IN ("%%A") do (
ren "%%~fA" "!filename:%%B =!"
)
)
which is more accurate and renames all files correctly only if they have the format mentioned in the beginning.
#echo off turns command-echoing off.
setlocal EnableDelayedExpansion enables delayed expansion. We use it only here, as we have to access variables inside a for loop which is a code block. You must use delayed expansion always inside these code blocks.
Now we make a for loop to parse the output (/F) of the dir /b /A-D command which lists all items in current working directory (%cd%), excluding directories (/A-D).
We need to set a variable here with the filename. We could use the variable name of the loop (%%A), but variables have an advantage: %var:search=replace%, or even !var:search=replace! which we need here.
Now we make another for loop to parse a string (/F): the filename (%%A). We need to access the first token to substract it later. We don't really need to specify it here, but it is good to make it clearer.
We rename files now: %%~fA is the full path where filename currently processed is and !filename:%%B =! means to take filename environment variable, search for string "%%B " (first part of filename [digits] and a space) and replace it with an empty string; actually nothing!

An easier solution is to use
all digits and space as delims and
tokens=*
:: Q:\Test\2019\01\06\SO_54054587.cmd
for /F "delims=" %%A in (
'dir "* *" /A-D-H /B 2^>nul'
) do for /F "tokens=* delims=0123456789 " %%B in (
"%%A"
) do ren "%%A" "%%B"
this will remove all leading delimiters while not splitting the remainder of the file name.
Like the other answers this will not account for the shorted file name already being present.

Your question is not specific enough for us to provide a solution, you really need to provide the section of code into which you wish this to be integrated.
This one expects only one file, as in your question, and that file must be named in the format you've indicated, i.e. the required part is separated from the non-required part by a space:
#Set "name=7612372 filename 50x50.jpg"
#Ren "%name%" "%name:* =%"
[Edit /]
I have noted from your comments that you were indeed looking to parse several files and those files did not match the naming scheme you provided in your question.
Here therefore is an updated potential solution based on those changed parameters.
#For %%A In (*.*) Do #For /F "Tokens=* Delims=0123456789 " %%B In ("%%A") Do #Ren "%%~A" "%%B"
Apologies to LotPings, who I've noticed has posted a very similar method/solution

It's very simple with the basic DOS command rename.
7612372 filename 50x50.jpg
If this is your sample file in the folder, it contains 7 digits and 1 blank space. Totally 8 characters.
We can do this by simply running this command on the particular folder
rename "*.mp3" "////////*.mp3"
each / represents a character you want to remove. That's it.

I suggest following batch code for this task:
#echo off
for /F "delims=" %%A in ('dir "* *" /A-D-H /B 2^>nul') do for /F "tokens=1*" %%B in ("%%A") do ren "%%A" "%%C"
pause
The command FOR runs with cmd.exe /C (more precise %ComSpec% /C) in a separate command process in background the command line:
dir "* *" /A-D-H /B 2>nul
DIR outputs to handle STDOUT of this background command process
just the names of all non-hidden files because of option /A-D-H (attribute not directory and not hidden)
in bare format because of option /B without file path
matching the wildcard pattern * * which matches any file name with at least one space inside
in current directory which can but must not be the directory of the batch file.
DIR would output an error message to handle STDERR if it can't find any directory entry matching these criteria. This error message is redirected to device NUL to suppress it.
Read the Microsoft article about Using Command Redirection Operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded dir command line with using a separate command process started in background.
FOR captures all lines output to handle STDOUT of started command process and processes those lines after started cmd.exe terminated itself. It is very important for this file renaming task that FOR runs on a list of file names captured before doing the file renames as otherwise the directory entries would change while FOR is accessing them. For that reason for can't be used directly in this case because of for would process the list of * * directory entries while this list changes on each successful file rename. The result would be files not renamed or renamed multiple times or even an endless running loop depending on file system (NTFS or a FAT file system like FAT32 or ExFAT).
FOR with option /F ignores empty lines which do not occur here. FOR ignores also lines starting with a semicolon because of end of line option eol=; is the default. But all lines output by DIR should start with a number and for that reason the default end of line definition can be kept for this task.
FOR with option /F splits up a line by default to substrings using normal space and horizontal tab as delimiters and assigns just first space/tab separated string to specified loop variable. This line splitting behavior is not wanted here in outer FOR loop because loop variable A should hold complete file name with all spaces. Therefore delims= is used to define an empty list of delimiters to disable the line splitting behavior. Safer would be "delims= eol=" which defines also no end of line character.
The file name assigned to loop variable A is referenced with %%A as string in inner FOR loop which splits up the file name into two substrings (tokens). The first substring is the number assigned to specified loop variable B. The second substring after first sequence of spaces (tabs not possible in a file name) is assigned without any further splitting to next loop variable C according to ASCII table. In other words on file name 7612372 filename 50x50.jpg loop variable B holds 7612372 and filename 50x50.jpg is assigned to loop variable C.
The command REN renames the file by referencing complete file name as assigned to loop variable A to the part after first sequence of spaces as assigned to loop variable C.
The command PAUSE at end is added to see the error message output by command REN if renaming a file failed. There is nothing output except the prompt by PAUSE on all files could be renamed successfully.
The batch code can be enhanced further by using FINDSTR as filter to make sure that a file to rename starts really with one or more digits up to first space by using this code:
#echo off
for /F "delims=" %%A in ('dir "* *" /A-D-H /B 2^>nul ^| %SystemRoot%\System32\findstr.exe /R /C:"^[0123456789][0123456789]* "') do for /F "tokens=1*" %%B in ("%%A") do ren "%%A" "%%C"
pause
One more variant for renaming a file with name 03T30 NAME T ALL 40X40X2 - Copy.JPG to T30 NAME T ALL 40X40X2 - Copy.JPG:
#echo off
for /F "delims=" %%A in ('dir /A-D-H /B 2^>nul ^| %SystemRoot%\System32\findstr.exe /R "^[0123456789][0123456789]*"') do for /F "tokens=* delims=0123456789 " %%B in ("%%A") do ren "%%A" "%%B"
pause
DIR outputs the names of all non-hidden files in current directory. This output is redirected as input for FINDSTR which checks if the file name starts with one or more digits. Only those file names are output to STDOUT of background command process to be processed next by FOR.
The inner FOR interprets all digits and space character as string delimiters because of delims=0123456789  and assigns everything after first sequence of digits or spaces to loop variable B because of tokens=*. So loop variable B holds filename 50x50.jpg with 7612372 filename 50x50.jpg assigned to A and T30 NAME T ALL 40X40X2 - Copy.JPG for file name 03T30 NAME T ALL 40X40X2 - Copy.JPG.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
dir /?
echo /?
findstr /?
for /?
pause /?
ren /?
PS: I recommend the usage of the shareware file manager Total Commander which has a built-in multi-rename tool for renaming files and folders for people with no coding experience. Download, install and start Total Commander, navigate to the folder containing all these files, press Ctrl+A to select the files, press Ctrl+M to open multi-rename tool window and the rest is self-explaining. If you need nevertheless help, press key F1 to open the help page for multi-rename tool.

Related

Delete string in multiple files in directory with cmd

:-)
I'm very new to cmd-commands and .bat-stuff, so would be grateful if any of you could help me with a problem.
So...I have a folder with 116 .txt files.
All these .txt files contain lines starting with a "#" and some other lines starting with "---".
I figured that findstr /v /L /C:"#" test.txt > test2.txt works in creating a new file without any lines that contain "#"
Now my question, is it possible to write something like findstr /v /L /C:"#" & "---" *.txt > *.txt ?
The goal is that each existing file is overwritten and all lines containing either "#" or "---" are removed.
Glad for any help!
Cheers,
Dyz
#ECHO OFF
SETLOCAL
rem The following setting for the source directoryis a name
rem that I use for testing and deliberately include names which include 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\t w o"
FOR /f "delims=" %%w IN ('dir /b /a-d "%sourcedir%\*.txt"') DO FINDSTR /v /L /c:"#" /c:"---" "%sourcedir%\%%w">"%sourcedir%\tempfile"&MOVE /y "%sourcedir%\tempfile" "%sourcedir%\%%w" >nul
GOTO :EOF
The meat of the matter is the for/f line, obviously.
Run dir /b to obtain a list of the filenames. /a-d excludes directorynames. This list is built in memory first, as the .txt files are being replaced - this ensures that the files are only "listed" once.
The for /f "delims=" reads that list and assigns each line-contents (filename+extension only) to %%w. The delims= ensures that filenames containing spaces are properly processed.
Then execute the findstr, which can take multiple /c: arguments to or the strings.
[I haven't tried it, but FINDSTR /v /L "# ---" "%sourcedir%\%%w" should produce identical processing]
The output of the findstr is directed to a temporary filename (I chose to put it in the source directory, but it could be anywhere with any name) and then the temporary file is moved over the original with the 1 file moved message suppressed by a >nul.
As always, test first on a copied sample.

How to delete the oldest file in a folder?

I am writing a batch script to backup files and want to include logic that deletes the oldest file in the folder if the number of backups ever exceeds a certain number set by a variable. Pretty new to batch and my current code deletes all files once it exceeds the number.
Any ideas how to do this?
SET Count=0
FOR %%A IN ("%SNAPSHOTNAME%*.*") DO SET /A Count += 1
IF %Count% gtr %NumberOfBackups% FOR %%A IN ("%SNAPSHOTNAME%_PBCS_Test_*.*") DO del "%%A"
I suggest the following single command line for this task:
for /F "skip=%NumberOfBackups% eol=| delims=" %%I in ('dir "%SNAPSHOTNAME%_PBCS_Test_*.*" /A-D-H /B /O-D 2^>nul') do del "%%I"
FOR executes in a separate command process started with cmd.exe /C in background the command line:
dir "%SNAPSHOTNAME%_PBCS_Test_*.*" /A-D-H /B /O-D 2>nul
DIR outputs to handle STDOUT line by line
just non-hidden files because of /A-D-H (not attribute directory or hidden)
in bare format because of /B which means file name only
ordered by last modification (write) time with newest file first and oldest file last.
An error message output by DIR to handle STDERR is suppressed by redirecting it to device NUL with 2>nul.
Read also the Microsoft article about Using Command Redirection Operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded dir command line with using a separate command process started in background.
FOR captures this output and processes it line by line according to the options specified in the double quoted string with ignoring empty lines which do not exist in this output of DIR.
The first %NumberOfBackups% lines are skipped by FOR which means the newest %NumberOfBackups% are always kept in current directory.
FOR by default ignores also lines starting with a semicolon because of ; is the default for end of line character. For that reason eol=| is used to change end of line character to vertical bar which is not possible in a file or folder name and so it is impossible that a file name output by DIR starts with |.
FOR by default splits a line into substrings using normal space and horizontal tab character as string delimiters and assigns just first space/tab separated string to loop variable I. This string splitting behavior can be disabled by specifying an empty list of delimiters with delims= at end of the options string to get the entire line (= file name) assigned to the loop variable I.
So DIR outputs the names all non-hidden files matching pattern "%SNAPSHOTNAME%_PBCS_Test_*.*" line by line with newest file first and oldest file last and FOR ignores the first/newest %NumberOfBackups% files and deletes all other older files.
FOR does nothing if DIR outputs less or exactly %NumberOfBackups% file names.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
del /?
dir /?
for /?
Note: This is nearly the same answer as written by Squashman, but with full explanation how it works.
If you change to using a FOR /F command with the SKIP option, you can get rid of the IF comparison.
set "NumberOfBackups=6"
FOR /F "SKIP=%NumberOfBackups% DELIMS=" %%G IN ('DIR /A-D /B /O-D "%SNAPSHOTNAME%_PBCS_Test_*.*"') DO DEL "%%G"
Your second for loop has no sort and no break condition so as mentioned by you it will delete all files.
A dir command can sort the files so instead of taking the for over all files take a for over the sorted output of an dir command. Option /OD will sort for file timestamp.
To let for loop handle the output use for /f. The break condition is to only delete the first (in this case the oldest) file and than jump out the for loop.
IF %Count% gtr %NumberOfBackups% for /f "delims=" %%f in ('dir /B /OD "%SNAPSHOTNAME%_PBCS_Test_*.*"') do del "%%f" & goto :gotIt
:gotIt

Moving multiple files in a single directory based on filename to multiple folders

First of all thank you in advance for the assistance. What I was trying to do is this:
1) I have a folder containing files with names:
122098_482056_1453458.xls
122098_482057_1453459.jpg
122098_482057_1453460.xls
122098_482056_1453457.jpg
2) I want to move these files to folders that I have created with names:
PO_90_122118_0_US
PO_90_122122_0_US
PO_90_122098_0_US
Note: The 3rd part of the folder's name matches with first part of the name of the files.
I have tried the following script which resulted in an error respectively has done nothing.
I have used delims=_ as my file names are delimited by the character _.
tokens=1 is used so that the first part of the file name is used.
#ECHO OFF
SETLOCAL
SET "sourcedir=D:\2009\2nd step batch - Copy"
SET "destdir=D:\2009\1st step batch"
FOR /f "delims=_" %%I IN (
'dir /b /ad "%destdir%\*" '
) DO (
FOR /f "tokens=1delims=(" %%s IN ("%%~I") DO (
IF EXIST "%sourcedir%\%%s*" ECHO(MOVE "%sourcedir%\%%s*" "%destdir%\%%I\"
)
)
GOTO :EOF
This batch file does not output any line which means there is no file found to move and I don't know why.
What is wrong in batch code to move all 122098_* files to folder PO_90_122118_0_US?
Here is your batch code rewritten for this task.
#ECHO OFF
SETLOCAL
SET "SourceDir=D:\2009\2nd step batch - Copy"
SET "DestDir=D:\2009\1st step batch"
FOR /F "tokens=1-3* delims=_" %%A IN ('DIR /AD /B "%DestDir%\*" 2^>nul') DO (
IF EXIST "%SourceDir%\%%C_*" MOVE "%SourceDir%\%%C_*" "%DestDir%\%%A_%%B_%%C_%%D\"
)
ENDLOCAL
You might insert ECHO left to MOVE for testing the batch file before really moving the files in a second run without ECHO.
For each subdirectory found in destination directory the directory name is split up into 4 tokens using underscore as delimiter.
PO is assigned to loop variable A as defined on FOR command line.
90 is assigned to next loop variable in ASCII table which is B.
122098 or the other numbers of real interest are assigned to loop variable C.
And last everything after third underscore in subdirectory name is assigned to loop variable D without further splitting up.
The IF condition checks if there is any file starting with the number from subdirectory name assigned to loop variable C and an underscore. The appropriate files are moved if this condition is true.
It is important to specify as destination directory all 4 parts of the subdirectory name, i.e. the complete name of the current subdirectory.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
echo /?
endlocal /?
for /?
if /?
move /?
set /?
setlocal /?
2^>nul redirects the confusing error message output by command DIR to handle STDERR in case of no subdirectory found to the device NUL to suppress it. The redirection operator > must be escaped here with ^ to be interpreted as redirection operator on execution of command DIR and not as misplaced redirection operator for command FOR. See also the Microsoft article Using command redirection operators.

Why does batch file for "Send To" to get all file names of a folder with space in path not work?

I need to get the names of all files within a folder to do a compare in Excel. I have this working and set up as a Send To feature. However, if the folder I right click on contains a space, it fails. Here is what I have:
#echo off
for /f "tokens=2 delims=:." %%x in ('chcp') do set cp=%%x
chcp 1252>nul
set dirpath=%1
dir %dirpath% dir /b /a | sort > "%dirpath%\FolderContents.txt"
chcp %cp%>nul
exit
Why are the file names not written to "Selected Folder\FolderContents.txt" if folder path contains 1 or more spaces?
There are several mistakes in those few lines of batch code.
The line with command DIR contains the command twice.
As the last paragraph output after several pages on running cmd /? in a command prompt window explains, a file/folder name (and other parameter strings) must be enclosed in double quotes if there is in name or path a space or one of the following characters: &()[]{}^=;!'+,`~
Therefore first argument of batch file on execution is enclosed in quotes if folder name contains a space. set dirpath=%1 assigns the folder name with the quotes to the environment variable dirpath. This results on next line in ""C:\Folder With Space"\FolderContents.txt" which can't be processed by command processor as expected by you.
A number left to redirection operator > could easily result in getting it interpreted as handle number. Although code page numbers are large enough to be not interpreted as handle number, it is better to have a space left to last redirection operator > in your code as %cp% is replaced by a code page number.
A really working and additionally simplified code for your task is:
#echo off
for /F "tokens=2 delims=:." %%x in ('chcp') do set "cp=%%x"
chcp 1252 >nul
dir "%~f1" /A-D /B /ON >"%~f1\FolderContents.txt"
chcp %cp% >nul
exit
The command DIR outputs just
the names of files because of option /A-D
in bare format because of option /B
ordered by name because of option /ON
and without path because of not using option /S for getting a list with all subdirectories included.
%~f1 is replaced by command processor by name of folder with full path without quotes.
Well, determining active code page of this and only this command process and restoring the code page before exiting entire command process is also not really needed in my point of view and therefore second and last but one line are also not necessary.
This variant of above writes the file names with path into the text file.
#echo off
chcp 1252 >nul
del "%~f1\FolderContents.txt" 2>nul
for /F "delims=" %%I in ('dir "%~f1" /A-D /B /ON 2^>nul') do (
>>"%~f1\FolderContents.txt" echo %~f1\%%I
)
exit
The redirection operator >> is now left to command echo to avoid that a file name ending very unlikely with  1,  2, ... is interpreted as handle number. A separating space can't be used here as this space would be also written into the file as being taken by command echo which would result in a trailing space on each file name in text file.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /?
chcp /?
dir /?
echo /?
exit /?
for /?
set /?
See also Microsoft article about Using command redirection operators.

Windows Command batch script to add filename to end of each row in a merged text file

I a new to windows command line scripts.
I have a batch file which i use to merge multiple text files into one. However i want to be able to also add the name of the text file the row comes from to the end of each row in the merged file.
This is the script i am currently working with:
#ECHO OFF
ECHO Creating %1...
FOR /F "usebackq tokens=1" %%G IN (`DIR /B "C:\My Documents\Data\*.txt"`) DO
(
ECHO Adding %%G
ECHO. >> Output.txt
TYPE %%G >> Output.txt
)
Now i know that to get the filename into the output file i need to use:
ECHO %%G >> Output.txt
However i'm not sure how i would add this to the current script so it adds the filename to each row and I have had no luck with finding any examples.
There is a simple two liner that works from the command line if you are willing to prefix each line with the file name instead of putting the file name at the end. This solution is extremely fast.
cd "C:\My Documents\Data"
findstr "^" *.txt >output.log
Each line will have the format of filename:line content
It is important that your output file use a different extension than the files you are merging. Otherwise you run the risk of the command processing its own output!
The other option is to make sure the output goes to a different folder, perhaps the parent folder:
cd "C:\My Documents\Data"
findstr "^" *.txt >..\output.txt
Or, if you are willing to include the full path to each file in your output, then make sure current directory is not the same as your source, and use
findstr "^" "C:\My Documents\Data\*.txt" >output.txt
The only drawback to the above solution is that problems can arise if the last line of a text file does not end with a newline character. This will cause the first line of the next file to be appended to the last line of the prior file. Something like: FILENAME1:last line without newlineFILENAME2:first line of next file
A simple script can append a newline to files that are missing the newline on the last line. Then the files can be safely merged with the filename prefix on each line:
#echo off
if "%~1" equ ":FindFiles" goto :FindFiles
cd "C:\My Documents\Data"
:: Append newline to text files that are missing newline on last line
for /f "eol=: delims=" %%F in ('"%~f0" :FindFiles') do echo(>>"%%F"
:: Merge the text files and prefix each line with file name
findstr "^" *.txt >output.log
exit /b
:FindFiles
setlocal enableDelayedExpansion
:: Define LF to contain a newline character
set lf=^
:: The above 2 blank lines are critical - do not remove
:: List files that are missing newline on last line
findstr /vm "!lf!" *.txt
You'll need to add each line in the file individually:
#ECHO OFF
ECHO Creating %1...
SET "sourcedir=c:\sourcedir"
FOR /F "delims=" %%G IN ('DIR /B /a-d "%sourcedir%\*.txt"') DO (
ECHO Adding %%G
ECHO. >> Output.txt
for /f "usebackq tokens=*" %%a in ("%sourcedir%\%%~G") do (
Echo %%a - %%G >> Output.txt
)
)
Note in the second last line, the file name and the line is seperated by a -, you can replace this with whatever (don't forget to check for escaping characters) or can get rid of this if you want.
I'm sure that will work, but if it doesn't, tell me the Error message and I can fix it for you.
Mona
---- [edit:pw]
Close - major problem was the ( on the FOR ... %%G line was on the line following the DO - must be on the same line as the DO.
Added /a-d to the DIR to prevent subdirectory names matching
changed "usebackq tokens=1" to use conventional quotes and allow spaces in filenames
assigned target directory name to sourcedir variable and included %sourcedir% in both FOR statements to allow execution from anywhere, otherwise the filenames found in C:\My Doc.... would be searched-for in the current directory for replication into the output.
OP needs to change value assigned to sourcedir to C:\My
Documents\Data

Resources