Using a variable for a file path in batch file - windows

I am very new to writing batch files, but I am trying to automate some data updating I have to do. I have the pdftotext.exe in a folder with a pdf file that I get each month. I was hoping to use a wildcard in the batch file so that I don't have to change the code each month. So right now I run:
pdftotext -raw -nopgbrk CO_Aug16.pdf
This will run the conversion with the pdf and the executable in the same folder, but if I try to use a wildcard in the filename:
pdftotext -raw -nopgbrk CO*.pdf
It looks for a file named that way, so I tried to create a variable called fname and put the wildcard in that name, but when I run:
set fname = "C:\Users\...\CO*.pdf"
pdftotext -raw -nopgbrk "%fname%"
It acts like it is trying to open a blank file, I get:
I/O Error: Couldn't open file ''
Is it possible for me to be able to use the wildcard? Sorry if this is a basic question, I just started learning to write in a batch file for this project.

Handling of wildcards is done by the applications, not by the terminal.
The approach I use is to find the files using dir *.pdf and then for each file call the command.
for /F "tokens=*" %%f in ('dir /b *.pdf') do pdftotext -raw -nopgbrk "%%~f"
If you're entering this in a batch file use 2 percentage signs. If you're writing direct into cmd then just use 1.
Description:
For /F - run a command for each line of another commands output
tokens = * - Put all the line content into %f
dir /b *.pdf = the command we loop over. Finds all pdfs. Only outputs the minimum of data.
Your command - the %%~f is the filename. The ~ strips any quote marks

Related

Run ffmpeg on all files of a folder [duplicate]

I need to convert some xls files into xlsx files. I can successfully convert one xls file into xlsx by running this command into cmd prompt (windows):
ssconvert inputFileName.xls outputFileName.xlsx
(ssconvert is a Gnumeric's command-line utility that can convert between different spreadsheet file formats)
I'd like to write a batch file that FOR EACH file in a specified directory runs the command I wrote above, using the current file name both for input and for output filename.
For example, if I have this set of files:
c:\directory\file1.xls
c:\directory\file2.xls
c:\directory\file3.xls
the output should be
c:\directory\file1.xlsx
c:\directory\file2.xlsx
c:\directory\file3.xlsx
so the batch pseudo code should be something like
directory = c:\directory\
for (fileName in directory)
ssconvert fileName.xls fileName.xlsx
Can anyone help me?
for /r %%v in (*.xls) do ssconvert "%%v" "%%vx"
a couple have people have asked me to explain this, so:
Part 1: for /r %%v in (*.xls)
This part returns an array of files in the current directory that have the xls extension. The %% may look a little curious. This is basically the special % character from command line as used in %PATH% or %TEMP%. To use it in a batch file we need to escape it like so: %%PATH%% or %%TEMP%%. In this case we are simply escaping the temporary variable v, which will hold our array of filenames.
We are using the /r switch to search for files recursively, so any matching files in child folders will also be located.
Part 2: do ssconvert "%%v" "%%vx"
This second part is what will get executed once per matching filename, so if the following files were present in the current folder:
c:\temp\mySheet.xls,
c:\temp\mySheet_yesterday.xls,
c:\temp\mySheet_20160902.xls
the following commands would be executed:
ssconvert "c:\temp\mySheet.xls" "c:\temp\mySheet.xlsx"
ssconvert "c:\temp\mySheet_yesterday.xls" "c:\temp\mySheet_yesterday.xlsx"
ssconvert "c:\temp\mySheet_20160902.xls" "c:\temp\mySheet_20160902.xlsx"
Actually this is pretty easy since Windows Vista. Microsoft added the command FORFILES
in your case
forfiles /p c:\directory /m *.xls /c "cmd /c ssconvert #file #fname.xlsx"
the only weird thing with this command is that forfiles automatically adds double quotes around #file and #fname. but it should work anyway
you can run something like this (paste the code bellow in a .bat, or if you want it to run interractively replace the %% by % :
for %%i in (c:\directory\*.xls) do ssconvert %%i %%i.xlsx
If you can run powershell it will be :
Get-ChildItem -Path c:\directory -filter *.xls | foreach {ssconvert $($_.FullName) $($_.baseName).xlsx }
I am doing similar thing to compile all the c files in a directory.
for iterating files in different directory try this.
set codedirectory=C:\Users\code
for /r %codedirectory% %%i in (*.c) do
( some GCC commands )

Windows batch file renaming for batch rendering

I have a number of files inside a folder that I am trying to run through a batch render command for command line rendering. The batch works, but I want to access the name of each file and set it as output name for the generated png file. Here is my batch command:
set process_dir=%CD%
C:
cd C:\solidangle\mtoadeploy\2016\bin
for /r %process_dir% %%f in (*.*) do kick -set defaultArnoldDriver#driver_png.RGBA.filename "C:\Arnold\batch\file_name.png" -l ../shaders -dw -v 4 -t 6 %%f
so for example in the path "C:\Arnold\batch\file_name.png" I want to replace the 'file_name' with the name of the file that is executed in order to produce that png file. Any help would be much appreciated!
I am not familiar with the render application you are using but I can suggest you the following way.
Replace file_name with %%~nf in your example.
To learn more about this feature and other read help with
FOR /?

Windows Batch script to rename files with it's folder name within a for loop

I have a bunch of .flv files in subdirs and I need to loop through them and rename it according to its path.
I was able to loop through them all, but I don't know how to split the path and rename it using batch script.
Here's what I have so far:
echo off
for /R %%F in (*.flv) do (
echo %%~pF
)
The "echo %%~pF" prints the path for the current file on the loop, something like this:
\folder\morefolders\activity\ NameThatIwant \Videos\
I tried spliting with "delims=\" on my for loop but I get only "echo off".
I tried other tutorials, read other questions on SO but none of them were renaming the files from a split string from the path of the file in the loop.
Could you guys help giving suggestions or direct me to any material that explains those %% codes?
Thanks.
I think you do not need to split the path, though you could do it using for /f "delims=NameInthePath tokens=1", where NameInthePath - is some word in the path and tokens= gives you the first part of the path separated by delims.
Actially, if you need to rename file name you need to use REN command. If you need to change the path for the flv file - use copy of move command.
A batch file to rename all .LOG files to .TXT in the 'demo' folder and all sub-folders:
CD C:\demo\
For /R %%G in (*.LOG) do REN "%%G" "%~nG.TXT"

Win 7: CMD batch file for creating directories based on filenames

I'm working on a CMD line batch file in a Win7 environment that will create directories based upon the filenames listed in a directory.
I am using this code, but the output created is partial and incomplete with only
setlocal enabledelayedexpansion
for /r %%i in (*.wav) do (
set filename1=%%i
set folder1=!filename1:~4,10!
mkdir !folder1!
)
pause
I have this script saved as a CMD file in text format in the source directory, on a local harddrive, though it is in a subdirectory.
The directory output is partial and broken, with garbled output and the numbers of directories created does not match the number of files, and the created directories seem to nest. I've researched this and can't seem to find a definitive answer.
It's not entirely clear what it is you are trying to accomplish. Are you trying to create a directory within the same directory containing the wav file, just without the .wav extension? If so, you're missing some quotation marks and you're stripping the wrong end of the filename off. If that's what you are trying to accomplish, it can actually be done with a single command, no batch script needed. Type this at the command prompt:
for /r %I in (*.wav) do mkdir "%~pnI"
Of course, if you still want it in a batch script, use %%I and %%~pnI with double percents instead of single. See the last couple of pages of help for for an explanation of how %%~pnI works.

Archive files with certain extension

So I need a Windows Script that I can tell it a directory to go through and it will parse all sub-directories and while in each subdir, will archive all files with a certain file extension and keep it in the same subdir, then move onto the next one.
What's the best way to go about this? Perl Automation Scripting, AutoIt?
Any sample code you guys can give me?
Perl is more powerful than batch scripts but since Perl is not included with windows it seems overkill for tasks such as this one. This should for example work:
FOR /R C:\hello\ %%G IN (*.txt) DO "c:\Program Files\7-Zip\7z.exe" a %%G.zip %%G && del %%G
Note that you cannot do this directly in the prompt, you must save it as a .bat file. It is of course also possible to allow the user to specify the paths and extensions with command line like this:
FOR /R %1 %%G IN (%2) DO "c:\Program Files\7-Zip\7z.exe" a %%G.zip %%G && del %%G
More information about FOR and other windows command line commands can be found here: http://ss64.com/nt/
This would then be run with:
test.bat C:\Hello\ *.txt
EDIT: This obviously requires you to have 7-Zip installed but it's pretty obvious where to change the code if you want to use some other zipper. Also keep in mind to always be Extremely careful when experimenting with scripts such as this. One small mistake could have it delete a lot of files, so you should always test it on a copy of the file system until you are absolutely sure it works.
FORFILES is included with Windows and may be more applicable than FOR to what you're trying to do:
FORFILES [/P pathname] [/M searchmask]
[/S]
[/C command] [/D [+ | -] {MM/dd/yyyy | dd}]
Description:
Selects a file (or set of files) and executes a
command on that file. This is helpful for batch jobs.
Parameter List:
/P pathname Indicates the path to start searching.
The default folder is the current working
directory (.).
/M searchmask Searches files according to a searchmask.
The default searchmask is '*' .
/S Instructs forfiles to recurse into
subdirectories. Like "DIR /S".
/C command Indicates the command to execute for each file.
Command strings should be wrapped in double
quotes.
The default command is "cmd /c echo #file".
The following variables can be used in the
command string:
#file - returns the name of the file.
#fname - returns the file name without
extension.
#ext - returns only the extension of the
file.
#path - returns the full path of the file.
#relpath - returns the relative path of the
file.
#isdir - returns "TRUE" if a file type is
a directory, and "FALSE" for files.
#fsize - returns the size of the file in
bytes.
#fdate - returns the last modified date of the
file.
#ftime - returns the last modified time of the
file.
To include special characters in the command
line, use the hexadecimal code for the character
in 0xHH format (ex. 0x09 for tab). Internal
CMD.exe commands should be preceded with
"cmd /c".
/D date Selects files with a last modified date greater
than or equal to (+), or less than or equal to
(-), the specified date using the
"MM/dd/yyyy" format; or selects files with a
last modified date greater than or equal to (+)
the current date plus "dd" days, or less than or
equal to (-) the current date minus "dd" days. A
valid "dd" number of days can be any number in
the range of 0 - 32768.
"+" is taken as default sign if not specified.
Below one way I would do it in AutoIt since you asked. Replace the MsgBox line with whatever code you need to do whatever it is your wanting to do. AutoIt is fun stuff!
#include <File.au3>
archiveDir(InputBox("Path","Enter your start path."))
Func archiveDir($rootDirectory)
$aFiles = _FileListToArray($rootDirectory)
For $i = 1 To UBound($aFiles) - 1
If StringInStr(FileGetAttrib($aFiles[$i]),"D") Then archiveDir($rootDirectory & $aFiles[$i] & "\")
MsgBox(0,"This would be your archive step!",'"Archiving" ' & $rootDirectory & $aFiles[$i])
Next
EndFunc
One solution could be:
my $dirCnt = 0;
traverse_directory('C:\Test');
sub traverse_directory{
my $directory = shift(#_);
$dirCnt++;
my $dirHandle = "DIR".$dirCnt;
opendir($dirHandle, $directory);
while (defined(my $file = readdir($dirHandle))){
next if $file =~ /^\.\.?$/; # skip . and .. ...
if (-d "$directory\\$file"){ traverse_directory("$directory\\$file"); }
if ($file =~ /\.txt/){ #find txt files, for example
print "$file\n"; #do something with the text file here
}
}
closedir($dirHandle);
}

Resources