batch script - run command on each file in directory - batch-file

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 )

Related

How to exclude files from compilation when using msvc (cl.exe)

I'm wondering how I would exclude a file from being built within my batch file. Currently, my cl.exe compiliation line within the batch file looks like this:
cl /c ..\source\*.c
so how would I say I would like to build all files EXCEPT "file_not_needed.c" from the build?
The file(s) with the file extension c to exclude can be temporarily renamed with changing the file extension to exclude them.
A single command line for a single C source code file for usage in a command prompt window or a batch file:
ren ..\source\file_not_needed.c file_not_needed.c.tmp & cl.exe /c ..\source\*.c & ren ..\source\file_not_needed.c.tmp file_not_needed.c
A multi-line solution for multiple C source code files for usage in a batch file:
for %%I in (file_not_needed "one more file not needed") do ren "..\source\%%~I.c" "%%~I.c.tmp"
cl.exe /c ..\source\*.c
for %%I in ("..\source\*.c.tmp") do ren "%%I" "%%~nI"
All the files to exclude must be specified inside the round brackets of first FOR loop using a space, comma or semicolon as separator between the file names without file extension.

How to write a batch file that can unzip a file into a new folder with the same name? [duplicate]

This question already has answers here:
How can I compress (/ zip ) and uncompress (/ unzip ) files and folders with batch file without using any external tools?
(6 answers)
Closed 9 months ago.
I need to write a batch script that will allow me to unzip a .zip file into a new folder that has the same name as the zip file. I cannot assume that I have some program to unzip the file; it has to work as if the computer is brand new.
For example, if I have a group of zip files named a1, b2, c3, and d4, I want their contents to go into 4 different folders labeled a1, b2, c3, d4. It doesn't need to be concise, it just has to work.
Read excellent topic How can I compress (zip) and uncompress (unzip) files and folders with batch file without using any external tools? written by npocmaka.
I suggest to use the second solution: Using Shell.Application
The task can be done with zipjs.bat also written by npocmaka with a batch file with just a few lines:
#echo off
for %%I in (*.zip) do call "%~dp0zipjs.bat" unzip -source "%%~fI" -destination "%%~dpnI\" -force yes
for /F "delims=" %%D in ('dir /AD /B "%TEMP%\*.zip" 2^>nul') do (
%SystemRoot%\System32\attrib.exe -h "%TEMP%\%%~D"
rd /S /Q "%TEMP%\%%~D" 2>nul
)
The hybrid batch file zipjs.bat must be in same folder as the batch file with the two lines above.
Running in a command prompt window call /? explains %~dp0 which means drive and path of argument 0 of batch file without surrounding quotes ending always with a backslash. Argument 0 of a called batch file is the name of the batch file, see also What does %~dp0 mean, and how does it work?
Help of command for displayed on running in a command prompt window for /? explains
%%~fI - full file/folder name without surrounding quotes, and
%%~dpnI - drive, path and name of a file/folder without surrounding quotes and without extension
for loop variables like call /? does for batch parameters/arguments.
The second for loop finds all subdirectories in directory for temporary files with .zip in directory name, removes the hidden attribute and deletes those subdirectories. This is necessary as zipjs.bat first extracts each file into a newly created subdirectory in directory for temporary files and leaves them there after successful extraction.

I wish to delete a line in a file containing a particular word. (*KEYWORD)

I wish to delete a line contaning a specific word (in my case it is [*KEYWORD]). Those files are having an extension '.blk'. These files are located in different subfolders in the same folder. I have written this followng code.
#setlocal enabledelayedexpansion
#echo off
dir "C:\Users\XFIWSM\Desktop\batch_files\T30\*.blk /s/b > dirlist.txt
for /F %%i in (dirlist.txt) do (
type %%i
findstr /v "KEYWORD"
> %%i.blk
)
pause
As per ansswer provided by Mr. Ken, i have tried with above code. But, nothing seems to work. i have created an empty file named dirlist.txt . But this file is also not being written with path of *.blk files. Also i wish to save the .blk file with same name at the same location. Therefore, i am trying to use > %%i.blk ... Can anyone please help me, where am i going wrong ?
You can't use type on files that aren't in the specified directory the way you are (your files are in subfolders of the specified directory, not in the directory itself).
My suggestion would be to use a dir command, with the appropriate switches to search subdirectories (/s) and to produce a bare listing (without sizes, dates, and folder/volume names) (/b), and redirect that to a text file. You can then use a for /f loop to read each line in that directory listing and process it further.
#setlocal enabledelayedexpansion
#echo off
dir "D:\Master\SPRINGBACK\DPK\T08\*.blk /s/b > dirlist.txt
for /F %%i in (dirlist.txt) do (
:: Process each file here
)
For information about removing a specific line of text from a file, you can see How to remove lines (or text in given lines) from file in batch?
if you have a machine with grep, (checkout unxutils on sourceforge if using windows), you could use this commmand:
grep "KEYWORD" -v *.blk > filewithlineremoved.blk

How to use subfolders with the FOR command?

I'm trying to use the FOR /f command to calculate the filesize of multiple files with the same extension. I have this so far:
FOR /F "usebackq" %%A IN ('C:\Users\%username%\*.bat') DO set size=%%~zA
If I have 3 batch files under the desktop, and 2 under my documents, I want the batch file to get the size of each and display all 5 together. I have the command working perfectly if I use just a single directory with batch files, but all I need is for it to include subdirectories. The current line I have above displays ECHO is off because there are NO batch files under the path C:\Users\%username%. I have batch files on my desktop, and I need it to include it since it's a subdirectory. How can I get this command to include subdirectories?
FOR /R
Loop through files (Recurse subfolders)
Syntax
FOR /R [[drive:]path] %%parameter IN (set) DO command
Key
drive:path : The folder tree where the files are located.
set : A set of one or more files. Wildcards must be used.
If (set) is a period character (.) then FOR will
loop through every folder.
command : The command(s) to carry out, including any
command-line parameters.
%%parameter : A replaceable parameter:
in a batch file use %%G (on the command line %G)
This command walks down the folder tree starting at [drive:]path, and executes the DO statement against each matching file.
If the [drive:]path are not specified they will default to the current drive:path.
Unlike some other variants of the FOR command you must include a wildcard (either * or ?) in the 'set' to get consistent results returned. In many cases you can work around this by adding a single character wildcard e.g. if you are looping through multiple folders to find the exact filename myfile.txt you could instead specify myfile.t?t
http://ss64.com/nt/for_r.html
dir is far easier.
dir "%userprofile%\*.bat" /a /s
or just the sizes
dir "%userprofile%\*.bat" /a /s|findstr /c:"File(s)"

Batch: Copy files from txt file into one folder

I am attempting to create a batch file to copy several files listed in a text file to a new folder. I have found several threads relating to this, but I can still not get the batch to work properly. The problem I am encountering is that the files listed in the txt are all in different source locations and have different extensions. The list reads, for example:
C:\Users\Foo\Pictures\Photographs\September\P1030944.jpg
C:\Users\Foo\Videos\Art\Movies\Class\movie.avi
C:\Users\Foo\Music\Jazz\20051.mp3
...etc
All the copy commands I could find have to list either the source directory i.e.
set src_folder=c:\whatever\
set dst_folder=c:\foo
for /f %%i in (File-list.txt) DO xcopy /S/E/U "%src_folder%\%%i" "%dst_folder%"
or the extension i.e.
for /R c:\source %f in (*.xml) do copy "%f" x:\destination\
but I need it to gather that information from the list itself.
If it helps I know that there are only files of a possible 39 different specific extensions in the txt (*.jpg *.gif *.png ... *.xhtml *.xht)
Any help/ideas?
Start reading HELP FOR and then try the following at the command prompt
FOR /F %a in (input.txt) DO #ECHO COPY %a c:\newfolder\%~nxa
you can see that %a gets expanded to the actual line in the input file, and that %~nxa is a way to extract the name and the extension from the file.
After careful testing, move the command to your BAT file, replace %a to%%a, and remove the ECHO command
#echo off
SET destfolder=c:\newfolder
FOR /F "delims=" %%a IN (input.txt) DO COPY "%%a" "%destfolder%\%%~nxa"
notice the wraping of the names with quotes "; and the inclusion of the "delims=" option; both are needed in case filenames contain blanks.
Finally be careful with possible name duplicates in the destination folder. If that is possible, you need to find an strategy to cope with such collisions. But this can be the subject of another SO question, can't it?
One sample which worked for me...
Replace my directories C:\whatever and C:\temp\svn with yours...
assuming that your filelist is named antidump_list.txt and located under C:\temp\svn\
> set src_folder=C:\whatever
> set dst_folder=C:\temp\svn
> for /f %%i in (C:\temp\svn\antidump_list.txt) DO copy "%src_folder%\%%i" "%dst_folder%\%%i"
Regards,
Gottfried
I have found that the easiest way to do this is to use a powershell script.
$Files = Get-Content File-list.txt
$Dest = "C:\output"
foreach ($File in $Files) {
Copy-Item $File $Dest
}
If you need to run it from a batch file, paste the above script to file named CopyFiles.ps1 and add the following command to your batch file
powershell -executionpolicy bypass -file .\CopyFiles.ps1
Since, powershell is included by default on Windows7 and newer, this method is as easy as doing the same with batch commands only.

Resources