I am trying to rename a bunch of files that have random characters at the beginning of the file name.
For example I have these: 63edaa55dfh33_Section1.pdf, 63edaa55dfh33_Section2.pdf, 63edaa55dfh33_Section3.pdf
I want to rename them to Section1.pdf, Section2.pdf and Section3.pdf.
The problem is the "63edaa55dfh33_" part may change so basically I want to remove everything up to and including the _ from every file. I tried using rename "*.pdf" "////*.pdf" as a test but it didn't work. The first 2 files were renamed properly with the first 4 characters removed but the 3rd file had the first 8 characters removed for some reason.
This solution may also not work because I don't always know the number of characters I want removed,that is why I want a way to say remove everything up to and including the _.
Run this on the command line in your pdf folder:
for /f "tokens=1,* delims=_" %a in ('dir /B *.pdf') do #echo %a_%b %b
That will give you a feel for how it works. Basically, the"tokens=1,* delims=_" causes the output from the dir /B *.pdf command to be split into pre and post delim parts (%a and %b respectively). In a batch script you need to double all the percent symbols:
#for /f "tokens=1,* delims=_" %%a in ('dir /B *.pdf') do #ren %%a_%%b %%b
Related
I've got some for loops iterating over files listed in a text file. They have two extensions, like filename.foo.bar.
The first loop goes:
for /F "tokens=*" %%A in (bars.txt) do decompressBars.exe %%A
This decompresses the .bar extension and leaves all the files as filename.foo. Next,
for /F "tokens=*" %%A in (bars.txt) do convertFoos.exe %%~nA %%~n~nA.baz
Here I'm trying to convert .foo files to .baz files with the convertFoos utility, but to do so I need to manipulate the %%A string to remove both file extensions, which I can't figure out how to do. I know that one ~n removes one extension, but two don't seem to remove two like I expected and I can't find a good way to do it. I would like to avoid scanning the folder for .foo files again as I might want to leave other .foo files in there untouched, but if there's no other reasonable way to do it I can avoid having other .foo files in the same folder.
You can remove the extension part twice, by making a call, that reinterprets its arguments:
for /F "tokens=*" %%A in (bars.txt) do decompressBars.exe %%A
for /F "tokens=*" %%A in (bars.txt) do call :convertFoos "%%~nA"
::Code should continue here
::Prevent reaching the "method"
exit /b
:convertFoos
convertFoos.exe %1 "%~n1.baz"
exit /b
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.
I am trying to get the file version of all the files inside a folder which I managed to do (but not in a good way) but now I want to stick the folder name along with the version so I would know which version is for which folder.
I am not very good in command line and only use it for some small tasks whenever I need it so my apology in advance..
Here is what I have done:
For /d %%a in (C:\high\low\*) Do (For /d %%* in (%%a) Do wmic datafile where name="%%~da\\high\\low\\%%~nx*\\bin\\Services.dll" get Version /value)
and I get output as:
`Version=2.2.0.1 Version=2.2.0.4 Version=2.2.0.4....Version=2.2.0.4
there are 20 folders under C:\high\low and I want to go into the bin directory of each sub folder so I can see which folder has been upgraded and which one is not.
Edit
There are more than 20 folders and structure is like this:
C:\high\low\office.Services.Bolton\bin\Services.dll
C:\high\low\office.Services.Slough\bin\Services.dll
C:\high\low\office.Services.Hull\bin\Services.dll
.
.
.
C:\high\low\office.Services.Cosham\bin\Services.dll
I want to check the version number of Services.dll and need the output as:
Bolton - 2.2.0.1
Slough - 2.3.0.1
Hull - 2.5.0.1
.
.
.
Cosham - 2.0.0.0
Thanks in advance..
Instead of stacking for /d you could do a dir /b/s to find all Services.dll and parse the nasty (cr,cr,lf) output of wmic with a for /f:
#Echo off&SetLocal EnableExtensions EnableDelayedExpansion
For /F "tokens=*" %%A in (
'Dir /B/S C:\high\low\Services.dll ^|findstr /i "bin\\Services.dll$"'
) Do (
Set "DLL=%%~fA"
Set "DLL=!DLL:\=\\!"
For /F "tokens=1* delims==" %%B in (
'wmic datafile where name^="!DLL!" get Version /value^|findstr Version'
) Do For /f "delims=" %%D in ("%%C") Do Echo Version: %%D %%~fA
)
The first For /f parses the output of the commamd inside the '' iterating through each line passed in %%A (I prefer upper case variables to better distinguish between lower case~ modifiers.
Since Dir will allow wildcards only in the last element I can't do a Dir /B/S C:\high\low\*\bin\Services.dll
To ashure I get only Services.dll in a bin folder I pipe dir output to findstr /i "bin\\Services.dll$ (findstr uses by default a limited RegEx so the \ has to be escaped with another one, the $ anchors the expression at the end of the line).
The wmic command needs the backslashes in the path also escaped what is possible with string substitution (works only with normal variables)
In a (code block) we need delayed expansion to get actual values for variables changed in the code block, so ! instead of % for framing the variable names
The 2nd For /f parses wmic output splitting at the equal sign, assigning content to var %%C
EDIT added another for /f to remove the wmic cr
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
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:::