I want to scan a folder whose path is defined by user input & finally apply ffmpeg to store all media files information into a text file. The following code does not work
#echo off
setLocal EnableDelayedExpansion
set /P "path=Enter folder path: "
dir %path% /B /O:N | findstr ".wmv$ .mpg$ .mkv$ .mpeg$ .mp4$ .avi$" >filename.txt
echo. >info.txt
for /f "tokens=* delims= " %%a in ('type filename.txt') do (
set in=%in%%%a
ffprobe "%path%!in!" 2>>info.txt
)
pause
However if I strip user input as follows the code does work?
#echo off
setLocal EnableDelayedExpansion
::set /P "path=Enter folder path: "
dir d:\Trainers\out\outt\ /B /O:N | findstr ".wmv$ .mpg$ .mkv$ .mpeg$ .mp4$ .avi$" >filename.txt
echo. >info.txt
for /f "tokens=* delims= " %%a in ('type filename.txt') do (
set in=%in%%%a
ffprobe "d:\Trainers\out\outt\!in!" 2>>info.txt
)
pause
The above script is placed in the folder containing ffprobe.exe & it successfully creates two txt files in the same directory
Note that d:\Trainers\out\outt\ is the directory to scan for media files & not the directory from where this bat file is executed
The basic syntax for ffprobe is
ffprobe "videofile"
Use a different variable name than path.
PATH already does something really important. So important, in fact, that your changing it is precisely why the script is breaking.
More specifically, when you try to execute a program using just a filename (no path at all), if the program cannot be found in the working directory, the contents of the PATH environment variable are searched. I haven't seen the error message you're getting, but it's probably failing to execute findstr, which is an executable typically found in a folder specified in PATH.
The user input command looks like the wrong context. Drop the quotes and it should work properly. The quotes are not needed to separate your prompt from your user input.
Related
I am trying to move files after sorting the files from one folder to another folder but I am always getting this exception "The System cannot find the path specified"
Below is my batch command code:
setlocal EnableDelayedExpansion
set destinationFolder=C:\Test_Actual_Queue
rem Create an array with filenames in right order
for /f "tokens=*" %%f in ('dir /b "C:\Test Print Queue\" ^| sort') do (
echo %%f
move %%f %destinationFolder%
)
pause
I am able to sort and display the file names in console but when I try to move to the destination folder , I am getting the above mentioned exception.
Both the folder paths are correct.
I tried debugging and this is the data I am getting in the console:
C:\TestFoder>setlocal EnableDelayedExpansion
C:\TestFoder>set destinationFolder=C:\Test_Actual_Queue
C:\TestFoder>rem Create an array with filenames in right order
C:\TestFoder>for /F "tokens=*" %f in ('dir /b "C:\Test Print Queue\" | sort') do (
echo %f
move %f C:\Test_Actual_Queue
)
C:\TestFoder>(
echo data1.Print_Job
move data1.Print_Job C:\Test_Actual_Queue
)
data1.Print_Job
The system cannot find the file specified.
C:\TestFoder>(
echo data2.Print_Job
move data2.Print_Job C:\Test_Actual_Queue
)
data2.Print_Job
The system cannot find the file specified.
what am I doing wrong here?
Looking forward to your solutions. Thanks in advance.
The command DIR with the arguments /b and "C:\Test Print Queue\" outputs just the names of all non hidden files and directories in specified directory without path. The current directory on execution of the batch file is C:\TestFoder which is a different directory than C:\Test Print Queue. For that reason the command MOVE cannot find the file/directory to move stored in C:\Test Print Queue specified without path in current directory C:\TestFoder and outputs the error message.
The command DIR would output the file/folder names with full path if additionally option /S is used to search also in subdirectories.
One solution is specifying source path also on MOVE command line:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "SourceFolder=C:\Test Print Queue"
set "DestinationFolder=C:\Test_Actual_Queue"
set "CreatedFolder="
if not exist "%DestinationFolder%\" (
md "%DestinationFolder%" 2>nul
if not exist "%DestinationFolder%\" (
echo Error: Failed to create folder "%DestinationFolder%"
goto EndBatch
)
set "CreatedFolder=1"
)
for /F "eol=| delims=" %%I in ('dir /A-D-H /B /ON "%SourceFolder%\*" 2^>nul') do (
echo Moving file "%SourceFolder%\%%I" ...
move "%SourceFolder%\%%I" "%DestinationFolder%\"
)
if defined CreatedFolder rd "%DestinationFolder%" 2>nul
:EndBatch
endlocal
pause
Command extensions are explicitly enabled as required for for /F although enabled by default. Delayed environment variable expansion is explicitly disabled as not needed for this task. Files with one or more exclamation marks in file name could not be successfully processed within the FOR loop if delayed environment variable expansion is enabled explicitly although not enabled by default and not needed here. Read this answer for details about the commands SETLOCAL and ENDLOCAL.
The batch file first creates the destination folder if not already existing with verifying if folder creation was successful.
The command FOR executes the command line
dir /A-D-H /B /ON "C:\Test Print Queue\*" 2>nul
in a background command process started with cmd.exe /C.
Command DIR outputs
just non hidden files because of /A-D-H which means all directory entries not having attribute directory or hidden set
in bare format because of /B which means just the file name with file extension and without file path
sorted by name because of /ON
found in directory C:\Test Print Queue matching the wildcard pattern * (any file).
It is possible that the source directory does not exist at all or does not contain any file matching the criteria. The error message output in these cases by DIR is suppressed by redirecting it from handle STDERR to device 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 with option /F as used here captures everything written to handle STDOUT of background command process and then processes the captured text line by line.
Empty lines are ignored by FOR, but DIR with the used options does not output empty lines at all.
Lines starting with ; would be also ignored by default by FOR. File names can start with a semicolon. For that reason option eol=| is used to change the end of line character from semicolon (default) to a vertical bar which a file name can't contain at all.
FOR would split up each line into substrings (tokens) using the default delimiters space and horizontal tab and would assign to loop variable I just the first space/tab delimited string. This splitting behavior is not wanted here and so option delims= is used to define an empty list of delimiters to disable the line splitting and get assigned to I always the entire file name even on containing one or more spaces. tokens=* could be also used to get entire line (= file name) assigned to I.
For each file output by DIR with name and extension, but without path, the name of the file is output and command MOVE is executed to move the file to destination folder without overwriting a file with same name in that folder because of option /Y is not used here.
Finally the batch file deletes the destination folder if it was created by the batch file and if it is still empty because there was no file to move at all.
Another solution would be changing the current directory to source directory.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
cd /D "C:\Test Print Queue" || goto EndBatch
set "DestinationFolder=C:\Test_Actual_Queue"
set "CreatedFolder="
if not exist "%DestinationFolder%\" (
md "%DestinationFolder%" 2>nul
if not exist "%DestinationFolder%\" (
echo Error: Failed to create folder "%DestinationFolder%"
goto EndBatch
)
set "CreatedFolder=1"
)
for /F "eol=| delims=" %%I in ('dir /A-D-H /B /ON 2^>nul') do (
echo Moving file "%%I" ...
move "%%I" "%DestinationFolder%\"
)
if defined CreatedFolder rd "%DestinationFolder%" 2>nul
:EndBatch
endlocal
pause
If command CD fails to change the current directory to source directory because of not existing, the well known error message is output:
The system cannot find the path specified.
Then the batch file jumps to the label EndBatch to restore previous environment and halt batch file execution until user presses any key.
On successfully changing the current directory the batch file continues and with command ENDLOCAL the initial current directory C:\TestFoder is set again as current directory for the command process executing the batch 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.
cd /?
dir /?
echo /?
endlocal /?
for /?
goto /?
if /?
md /?
move /?
pause /?
rd /?
set /?
setlocal /?
I am trying to create a batch file:
The batch file will locate the path of executable first. Then, the path will be stored in a variable for later use.
This is my code:
#echo off
setlocal
set directoryName=dir/s c:\ABCD.exe
rem run command
cmd /c %directoryName%
pause
endlocal
The command prompt does return me with the executable's path but the path is not stored in the variable. Why is it so?
Reading your question, it appears that you're not really wanting to save the path of the executable file at all, but the file name complete with it's full path:
I prefer the Where command for this type of search, this example searches the drive in which the current directory resides:
#Echo Off
Set "mPth="
For /F "Delims=" %%A In ('Where /R \ "ABCD.exe" /F 2^>Nul'
) Do Set "mPth=%%A"
If Not Defined mPth Exit /B
Rem Rest of code goes here
The variable %mPth% should contain what you need. I have designed it to automatically enclose the variable value in doublequotes, if you wish to not have those, change %%A on line 4 to %%~A. If the file is not found then the script will just Exit, if you wish it to do something else then you can add that functionality on line 5.
Note: the code could find more than one match, if it does it will save the variable value to the last one matched, which may not be the one you intended. A robust solution might want to include for this possibility.
Edit (this sets the variable, %mPth% to the path of the executable file only)
#Echo Off
Set "mPth="
For /F "Delims=" %%A In ('Where /R \ "ABCD.exe" /F 2^>Nul'
) Do Set "mPth=%%~dpA"
If Not Defined mPth Exit /B
Set "mPth=%mPth:~,-1%"
Rem Rest of code goes here
Lets walk through your code
set directoryName=dir/s c:\ABCD.exe
This fills the variable directory name with the value dir/s c:\ABCD.exe.
cmd /c %directoryName%
This executes the command in directoryname. There is no line in your code that saves the files location to a variable.
Extracting the path of a file can be done as follows
#echo off
setlocal
set executable=c:\location\ABCD.exe
FOR %%A IN ("%executable%") DO Set executablepath=%%~dpA
echo executablepath: %executablepath%
pause
endlocal
%executablepath% will contain c:\location\
The value that you are assigning to directoryname is dir /s c:\abc.exe.
this value is then substituted for %directoryname% in your cmd line, which executes the command dir/s..., showing you the location(s) of abc.exe in the familiar dir format.
If what you want is just the directoryname in directoryname, then you need
for /f "delims=" %%a in ('dir /s /B /a-d "c:\abc.exe"') do set "directoryname=%%~dpa"
which will first execute the dir command, then process each line of output from that command and assign it in its entirety to %%a.
The dir command shown would "display" the matching names found in the nominated directory (c:\) and its subdirectories (/s) in basic form (/b) - that is, names only, no size or date or report-headers or report-footers, and a-d without directorynames (should they match the "mask" abc.exe)
The delims= option to the for /f command instructs that the entire line as output by the command in single-quotes, be assigned to %%a.
When the result is assigned to the variable directoryname, only the Drive and Path parts are selected by using the ~dp prefix the the a.
Note that only the very last name found will be assigned to the variable as any earlier assignment will be overwritten by a succeeding assignment.
This may or may not be what you are looking for. This script searches through the PATH variable and looks for files that have and extension in the PATHEXT variable list.
#SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
#SET EXITCODE=1
:: Needs an argument.
#IF "x%1"=="x" (
#ECHO Usage: %0 ^<progName^>
GOTO TheEnd
)
#set newline=^
#REM Previous two (2) blank lines are required. Do not change!
#REM Ensure that the current working directory is first
#REM because that is where DOS looks first.
#PATH=.;!PATH!
#FOR /F "tokens=*" %%i in ("%PATH:;=!newline!%") DO #(
#IF EXIST %%i\%1 (
#ECHO %%i\%1
#SET EXITCODE=0
)
#FOR /F "tokens=*" %%x in ("%PATHEXT:;=!newline!%") DO #(
#IF EXIST %%i\%1%%x (
#ECHO %%i\%1%%x
#SET EXITCODE=0
)
)
)
:TheEnd
#EXIT /B %EXITCODE%
Note that this may find multiple executables. It may also find multiple types of executables. The current directory is also included first since that is what the shell, cmd.exe, does.
M:>whence wc
.\wc.BAT
.\wc.VBS
C:\Users\lit\bin\wc.BAT
C:\Users\lit\bin\wc.VBS
I have a question. Is it possibile in batch language to search in folder a part of name that is same like another file and display it.For example i got folder with files :
ggggggsss.mp3
ddddddeee.mp3
ddddddff.mp3
ssssssddd.mp3
aaaaasssss.mp3
11111ssdas.mp3
11111dddd.mp3
...
I need to display in cmd only names of files
ddddddeee
ddddddff
and
11111ssdas
11111dddddd
Because the first six letter are the same. Could someone help me with this problem?
Save this script to test.bat and run from open Cmd Prompt. Replace dir value with path to your folder with .mp3 files:
#echo off
setlocal enabledelayedexpansion
set "dir=%userprofile%\music"
set "pattern1=dddddd" & set "pattern2=11111"
pushd "%dir%"
FOR %%G IN (*.mp3) DO ( set song=%%G
if "!song:~0,6!"=="%pattern1%" echo %%G)
echo/
FOR %%G IN (*.mp3) DO ( set song=%%G
if "!song:~0,5!"=="%pattern2%" echo %%G)
popd
exit /b
See also Extract Substrings.
I'm trying to rename the latter part of a file, before the extension, in a batch script.
For instance:
block1.txt --> block1-%mydate%-%mytime%.txt
block2.zip --> block2-%mydate%-%mytime%.txt
The file name is passed to the program as %1. Only one file name will be changed per run. The program is intended to append a time-stamp to the end of a file, in the form of MMDDYYYY-HHMM.
The first part of the program produces the expression %mydate%-%mytime%.
I can't for the life of me figure out how to do it in a generic and consistently functional way.
Any help?
Did you mean: FileName-MMDDYYYY-HHSS.*
for /f "tokens=2-7 delims=/:. " %%a in ("%date% %time: =0%") do set newFileName=%~n1-%%a%%b%%c-%%d%%f%~x1
ren "%~1" "%newFileName%"
Or did you mean: FileName-MMDDYYYY-HHMM.*
for /f "tokens=2-6 delims=/:. " %%a in ("%date% %time: =0%") do set newFileName=%~n1-%%a%%b%%c-%%d%%e%~x1
ren "%~1" "%newFileName%"
For Windows here is what #hobodave answered to a similar question:
For command-line
for /F %i in ("c:\foo\bar.txt") do #echo %~ni
output: bar
For .bat Files
set FILE=bar
for /F %%i in ("%FILE%") do #echo %%~ni
output: bar
Further Reading:
http://www.computerhope.com/forhlp.htm
For Unix
You can use the basename command. It will clear path and extension from a given path.
basename /foo/bar/arch.zip .zip
Will output
arch
Basename manual: http://unixhelp.ed.ac.uk/CGI/man-cgi?basename
Here's my situation. A project has as objective to migrate some attachments to another system.
These attachments will be located to a parent folder, let's say "Folder 0" (see this question's diagram for better understanding), and they will be zipped/compressed.
I want my batch script to be called like so:
BatchScript.bat "c:\temp\usd\Folder 0"
I'm using 7za.exe as the command line extraction tool.
What I want my batch script to do is to iterate through the "Folder 0"'s subfolders, and extract all of the containing ZIP files into their respective folder.
It is obligatory that the files extracted are in the same folder as their respective ZIP files. So, files contained in "File 1.zip" are needed in "Folder 1" and so forth.
I have read about the FOR...DO command on Windows XP Professional Product Documentation - Using Batch Files.
Here's my script:
#ECHO OFF
FOR /D %folder IN (%%rootFolderCmdLnParam) DO
FOR %zippedFile IN (*.zip) DO 7za.exe e %zippedFile
I guess that I would also need to change the actual directory before calling 7za.exe e %zippedFile for file extraction, but I can't figure out how in this batch file (through I know how in command line, and even if I know it is the same instruction "cd").
EDIT #1
I have already received some tips on ServerFault to the same question. Please see the answers at this link.
However, it extracted from the root (C:), and not from the given in parameter folder.
Anyone has an idea?
EDIT #2
It seems that batch script doesn't handle folder and file names containing a space character adequately. Can anyone confirm what I think?
EDIT #3
I need it to be fully recursive, since I don't know the directory structure against which this will be used.
EDIT #4.a
With #aphoria's solution, I'm almost there! The only problem is that it takes let's say File5.zip, retrieve the filename only to get File5, creates a subfolder File5 and extract the File5.zip to File5 subfolder, then, it wants to create a File5 subfolder in Folder 1, where it should instead want to create File1 subfolder, to stick with my example.
EDIT #4.b
As required, here's the code as it currently look:
#echo off
setlocal enableextensions enabledelayedexpansion
rem
rem Display instructions when no parameter is given.
rem
if "%1" equ "" (
echo Syntaxe : od.bat ^<directory mask>^
echo Exemple : od.bat *
goto :Eof
)
rem
rem Setting the PATH environment variable for this batch file for accessing 7za.exe.
rem
path=c:\temp;%PATH%
rem
rem Removing quotes from the given command line parameter path.
rem
set root=%1
set root=%root:~%1
set root=%root:~0,-1%
rem Searching directory structure from root for subfolders and zipfiles, then extracting the zipfiles into a subfolder of the same name as the zipfile.
for /F "delims==" %%d in ('dir /ogne /ad /b /s %root%') do (
echo Traitement du dossier : "%%d"
for /F "delims==" %%f in ('dir /b "%%d\*.zip"') do (
rem Getting filename without extension.
set subfolder=~n%f
mkdir "%%d\%subfolder%"
rem Extracting zipfile content to the newly created folder.
7za.exe e "%%d\%%f" -o"%%d\%subfolder%"
)
)
:Eof
endlocal
Ideas anyone?
My guess is that it digs one directory hierarchy at a time. Here's the deal. Consider we have a Folder A in Folder 1 (Folder 1\Folder A), then, it searches from Folder 1 through Folder 5, and comes back to Folder 1\Folder A, where the %subfolder% variable sticks with its last value.
Anyone's help is gratefully appreciated.
I'm not very familiar with the 7zip command-line options, so you will need to figure out the exact command for that, but the script below will take a fully specified path (spaces allowed) and print out the the folder name and .zip files contained within it.
#ECHO OFF
REM
REM Remove the double quotes from the front and end of the root path
REM
SET ROOT=%1
SET ROOT=%ROOT:~1%
SET ROOT=%ROOT:~0,-1%
ECHO %ROOT%
FOR /F "DELIMS==" %%d in ('DIR "%ROOT%" /AD /B') DO (
ECHO %%d
FOR /F "DELIMS==" %%f in ('DIR "%ROOT%\%%d\*.zip" /B') DO (
ECHO %%f
)
)
Run it like this:
MyScript.CMD "c:\temp\usd\Folder 0"
You should get output similar to this:
Folder A
File 1.zip
File 2.zip
Folder B
File 1.zip
File 2.zip
UPDATE
The code below will extract Folder A\File 1.zip to a new folder Folder A\File 1.
A few things to keep in mind:
In the first FOR loop, you need to have %ROOT% enclosed in double quotes to handle folders with spaces in the name.
Since you're SETting a variable inside the second FOR, you need to put SETLOCAL ENABLEDELAYEDEXPANSION at the beginning. Then, reference the variable using ! (for example, !subfolder!) to force expansion at runtime.
This line of your code set subfolder=~n%f should be this set subfolder=%%~nf
I put ECHO in front of the MKDIR and 7za.exe commands to test. Once you are sure it is doing what you want, remove the ECHO statement.
Here is the code:
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
REM
REM Remove the double quotes from the front and end of the root path
REM
SET ROOT=%1
SET ROOT=%ROOT:~1%
SET ROOT=%ROOT:~0,-1%
ECHO %ROOT%
REM Searching directory structure from root for subfolders and zipfiles,
REM then extracting the zipfiles into a subfolder of the same name as the zipfile.
FOR /F "delims==" %%d IN ('dir /ogne /ad /b /s "%ROOT%"') DO (
ECHO Traitement du dossier : "%%d"
FOR /F "delims==" %%f IN ('dir /b "%%d\*.zip"') DO (
REM Getting filename without extension.
SET subfolder=%%~nf
ECHO mkdir "%%d\!subfolder!"
REM Extracting zipfile content to the newly created folder.
ECHO 7za.exe e "%%d\%%f" -o"%%d\!subfolder!"
)
)
ENDLOCAL