I have filenames in a directory in the format of Mumbai Short Call Agentwise-MUMBAI SHORT CALL-3-01092016. I would like to strip off everything after the second hyphen and keep the first portion of the filename.
Is there a good website that could direct me in how to accomplish this? Or, maybe one of you dos batch experts can lead me in how to do this?
for /f "tokens=1,2,* delims=-" %%a in ('dir /b *-*-*') do #ECHO ren "%%a-%%b-%%c" "%%a-%%b%%~xc"
for every file with the given mask *-*.*: get first (%%a) and second part (%%b) plus extension of the rest (rest: %%c; Extension of the rest:%%~xc)
Notes:
- if you shorten filenames, be aware of possible duplicates!
#ECHO just lists the rename commands. Remove #ECHO, if the output satisfies you
See for /? or for /f for more information
Related
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.
Have a quick question as below:
dir /b *. >>Index.txt
The above command can output all the current directories in a list into text file called index.txt.
However, the list are on the leftmost of each line, can we have some space at the beginning of each output lines at the index.txt?
I am looking for a batch file solution.
Any suggestions?
Depending upon your requirements, you could use something like this:
#(For /F "EOL=|Delims=" %%A In ('Dir /B/AD') Do #Echo %%A)>"Index.txt"
Or perhaps you would prefer to right align it too:
#Echo Off
Set "pad= "
( For /F "EOL=|Delims=" %%A In ('Dir /B/AD') Do ( Set "line=%pad%%%A"
Call Echo=%%line:~-24%%))>"Index.txt"
The latter example may need adjusting according to the number of characters in your directory names.
I'm currently trying to rename a multiple files using command prompt but I just can't get it work.
So this is what I'm trying to do.
I'm trying to renames these files
file_aaa_001.jpeg
file_bbb_002.jpeg
file_ccc_003.jpeg
To the following files:
001.jpeg
002.jpeg
003.jpeg
I know this is super beginner level, but I would be great if could get some help.
Edit: the sequences "aaa"s are not necessarily the same three letters, it could be any number of random letters.
So to be more clear, I want to delete the letters from the begging to the second "_". Thank you
Assuming you just need to takeout the prefix, use
ren "*.*" "/////////*.*"
If you want to be prudent and only take those prefixed with "file_", followed with three character and last dash before the sequence, and only those with jpeg extension
ren "file_???_*.jpeg" "/////////*.*"
As always, you want to backup the folder before running/modifying the commands.
Supposing there are always exactly two _ characters in each file name and there is at least one other character in between, you could use a for /F loop to split the file names:
for /F "eol=: delims=" %%F in ('
dir /B "*_*_*.jpeg"
') do (
for /F "tokens=2* delims=_" %%I in ("%%~nF") do (
rename "%%~F" "%%J%%~xF"
)
)
I am new to batch files and I only need a very simple thing done.
I would like a batch file to take a text file which is a list of filepaths --
Filelist.txt
Begin File>>
O:\X\Y\Z\Board BOM Rev 4.xls >>Files
O:\X\Y\U >>Entire filepaths
< End File
and then copy the files (not the names of the files, to clarify) to a given location.
Say that the batch file is in O:\X\Y\Z (And so is the text file), and I would like to copy all of those files to that folder. I have tried to use this code
#echo off
set input="O:\X\Y\Z\Filelist.txt"
set dest=%cd%
for /f %%i in "input" do xcopy "%%i" %dest%\ /S
To do what I need to do, but I get the aforementioned error. I have done very little with batch files, so corrections with explanations would be much appreciated!
Thanks!
First, to use your variable "input" write %input%
Second, for the correct format of for you have to put parantheses around it:
for /f %%i in ("%input%") do xcopy "%%i" %dest%\ /S
1st. (input)
In the first set you have double-quoted wrong the value, that formatting is for extraordinary cases, not this time.
2nd. (dest)
You need to ensure to double-quote every "variable=value" (at least when they are string variables and when can contains spaces)
but anyways you can simplify the code a little to don't depend on that dest variable,
3rd. (For)
The dest variable inside for has the same quote problem, also you are typing incorrectly the input variable, and for syntax can be improved to prevent future errors by agroupping the commands using the agroupation operators ().
Here is the code:
#echo off
set "input=O:\X\Y\Z\Filelist.txt"
REM set "dest=%cd%"
for /f "Usebackq Delims=" %%i in ("%input%") do (
xcopy "%%i" ".\" /S
)
PS: Forgive my English.
I tried to list all files and directories on a directory by using this format
dir1:::dir2:::file1:::file2:::
To achieve this, I wrote a batch script. Take a look at it :
#echo off
SETLOCAL ENABLEDELAYEDEXPANSION
SET M=
FOR %%d IN ('dir /B') DO SET M=!M!%%d:::
ECHO %M%
Well, it works for directories/files that doesn't contain spaces, but for those that contained it, it will show just the first word.
For example, suppose the files are "Blue hills.jpg" and "Sunset.jpg".
The expected result is of course
Blue hills.jpg:::Sunset.jpg:::
But what appears instead is
Blue:::Sunset.jpg
FYI, I use WinXP. *Is that matter? I've tried to put quotes in "%%d" but it doesn't work. How can I fix this?
Thanks for the help! And sorry for my bad english, I really have to improve it..
You need to run your for loop for file names containing any text (spaces included) "tokens=*". The /f switch is to search for text (filename text).
#echo off
SETLOCAL ENABLEDELAYEDEXPANSION
SET M=
FOR /f "tokens=*" %%d IN ('dir /B') DO SET M=!M!%%d:::
ECHO %M%
Works for files and directories with spaces.
If you use tokens=1 then you get the first word of each file name (using a space as separator). So you would see
Blue:::Sunset.jpg:::
If you use tokens=2 then you get the second word:
hills.jpg:::