batch file for runing a java command - batch-file

I have to run the following command for hundreds of .docx files in a directory in a windows in order to convert them to .txt.
java -jar tika-app-1.3.jar -t somedocfile.doc > converted.txt
I was wondering if there is any automatic way such as writing a ".bat" file to do this.

Yes you can do it in batch. An example isn't coming to mind in order to help you but since you are running java commands anyway you can do it through java too. Here is an example of how you can be running the commands on CMD from java. Hope this helps.
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
try {
executeCMD("java -jar tika-app-1.3.jar -t " + <YOUR_DOC_FILE> + " > " + <TXT_NAME_OF_FILE> );
}catch(Exception e){
e.printStackTrace();
}
private void executeCMD(String command) throws Exception{
Process process = Runtime.getRuntime().exec(command);
printMsg(command + " stdout:", process.getInputStream());
printMsg(command + " stderr:", process.getErrorStream());
process.waitFor();
if(process.exitValue() != 0)
System.out.println(command + "exited with value " + process.exitValue());
}
private void printMsg(String name, InputStream ins) throws Exception {
String line = null;
BufferedReader in = new BufferedReader(new InputStreamReader(ins));
while((line = in.readLine()) != null){
System.out.println(name + " " + line);
}
}
UPDATE
Okey here is the way simpler batch way which I couldn't think of yesterday :D
for /r %%i in (*.doc) do java -jar tika-app-1.3.jar -t %%~ni > %%~ni.txt
It reads all the *.doc files in the directory it is executed, also the "~n" is in order to list only the filenames ( in your example "somedocfile" ) because otherwise it will do something like "C://...../somedocfile.doc" and changing the extension might be annoying.

Related

How do you redirect squirrel "print" command output to a file?

I have a Squirrel plugin as below:
fe.add_transition_callback( "removefavourite" );
function removefavourite( ttype, var, ttime )
{
switch ( ttype )
{
case Transition.ChangedTag:
print( fe.game_info( Info.Name ) + "\n" );
system( "echo '" + fe.game_info( Info.Name ) + "' > /home/pi/.attract/romlists/ROMNAME.tmp" );
system( "printf '" + fe.game_info( Info.Emulator ) + "' > /home/pi/.attract/romlists/ROMNAME2.tmp" );
break;
}
return false;
}
fe.add_transition_callback( "removefavourite" )
I would like to redirect the output of the "print" command from terminal/console to a file. However, I cannot seem to do so and would be grateful if someone could assist me please.
I've tried alternatives in bash - many variations of the "echo" command and the "printf" command, but these are not effective to capture words which include parentheses eg () or single quotes eg '. The "print" command seems to be effective in all cases but I have not been able to redirect the output.
Please note that I am unable to modify the words I'm capturing first by escaping/backslashing special characters before sending them to print, echo or printf.
Thank you.
I managed to solve this problem I was having. I found "keeping it simple, stupid" and just having the plugin deal with one argument was the way to go.
I altered the plugin as follows:
fe.add_transition_callback( "removefavourite" );
function removefavourite( ttype, var, ttime )
{
switch ( ttype )
{
case Transition.ChangedTag:
fe.plugin_command( "/usr/bin/printf1.sh", "\"" + fe.game_info(Info.Name) + "\"" );
system( "sudo /bin/bash /opt/retropie/configs/all/removefavourite.sh" ); // Starts the process of removing the game from Favourites.txt
}
return false;
}
fe.add_transition_callback( "removefavourite" )
This plugin sends the game's name to a new bash script I created called "printf1.sh". The bash script goes in the same folder as the "printf" command which is in the "/usr/bin/" folder. The bash script has to go into this folder, otherwise there is a "chdir" (change directory) error.
The contents of the bash script are:
#!/bin/bash
FILE1=$1
sudo /usr/bin/printf "$FILE1" > "/home/pi/.attract/romlists/REMOVEFAVOURITE.temp"
Basically, the game name is the "argument" and that is sent from the squirrel plugin to the bash script which then redirects the game name (the output) to the file "REMOVEFAVOURITE.temp".
The benefit of this approach is that no matter what form the game name takes eg with a single apostrophe or () or [] like "Sam's Journey (c64)" or "Sam's Journey [c64]", the script will capture it and pass it on. Special characters make no difference.
From there, I can do whatever I like with the information recorded in "REMOVEFAVOURITE.temp".

unzipping a file using 7zip in SSIS

I'm currently using a Process Task to try to unzip a file in SSIS with the following settings:
I'm using this statement:
e "Inventory.zip" -o"c:\broinctarget\" -y
I'm actually generating the above statement using:
"e " +"\"" + "Inventory.zip" + "\"" + " -o" + "\"" +#[$Package::targetLocation] +"\""+" -y"
#[$Package::targetLocation]
Am I doing something that is obviously wrong?
How do I unzip a *.zip file using 7zip in SSIS?
I ran into a similar issue on an SSIS package I wrote. I ended up generating a batch file in a c# script, and just calling that batch file in an execute process task.
I also needed the flexibility to add a password option based on some table parameters.
I realize it's an extra step, and if I were unzipping a ton of files it might matter, but for a For-Each container that is going to hit 5-10 files, its not a big deal - and you can easily read the batch file to see what was run too.
string exe7z = Dts.Variables["s7ZIPPath"].Value.ToString();;
string zipFile = Dts.Variables["sZIPFile"].Value.ToString();
string outPath = Dts.Variables["sFileLocation"].Value.ToString();
string password = Dts.Variables["sZIPPassword"].Value.ToString();
if (password.Length > 0)
{
password = "-p\"" + password + "\"";
}
if (!(outPath.EndsWith("\\")))
{
outPath = outPath + "\\";
}
string batchFile = outPath + "unzip.bat";
Dts.Variables["sZipBatchFile"].Value = batchFile;
using (StreamWriter writer = new StreamWriter(batchFile))
{
writer.Write("\"" + exe7z + "\" e \"" + zipFile + "\" -o\"" + outPath + "\" -y " + password);
}

How do I run a gawk file with spaces in the path name?

I am trying to run the following line in an awk script and I am getting an error. I think the error is because the filename has spaces in it. How do I call the file without changing the path name (i.e. rename the file/path)? The code is contain within a BEGIN{} block.
INSTALLATION_LOCATION_GAWK = "L:/CPU_Analysis/Sanity/CPUAnalysisApp/cpu_analysis_application/"
DATA_SUMMARY_LOCATION_GAWK = "C:/Program Files/CPU Analysis/data/data_summary.csv"
....
command = ("gawk -v version=" dataArray[1] " -v date=" dataArray[2] " -v platform=" dataArray[3] " -f ") (INSTALLATION_LOCATION_GAWK "generateSanity_Scripts/removeData.awk ") DATA_SUMMARY_LOCATION_GAWK
system(command)
UPDATE: I also ran into the issue that you cannot copy/save/edit files in C:\Program Files due to windows restrictions. I solved this problem by moving my project to C:\My Programs.
I think it will be a case of providing quotes in the command string:
command = "gawk"
command = command " -v version=\"" dataArray[1] "\""
command = command " -v date=\"" dataArray[2] "\""
command = command " -v platform=\"" dataArray[3] "\""
command = command " -f \"" INSTALLATION_LOCATION_GAWK "generateSanity_Scripts/removeData.awk\""
command = command " \"" DATA_SUMMARY_LOCATION_GAWK "\""

Get image file dimensions in .bat file

I have a bat file that lists the paths of all images in a folder the code is
#echo off
break > infofile.txt
for /f "delims=" %%F in ('dir /b /s *.bmp') do (
echo %%F 1 1 1 100 100 >>infofile.txt
)
The text file looks like this
C:\Users\Charles\Dropbox\trainer\temp\positive\rawdata\diags(1).bmp 1 1 1 100 100
C:\Users\Charles\Dropbox\trainer\temp\positive\rawdata\diags(348).bmp 1 1 1 100 100
C:\Users\Charles\Dropbox\trainer\temp\positive\rawdata\diags(353).bmp 1 1 1 100 100
What I want to do is replace the 100 100 at the end by the dimentions of each image width and height.. Thanks in advance.
you can use MediaInfo:
#ECHO OFF &SETLOCAL
(for /r %%a in (*.jpg *.bmp *.png) do (
set "width="
set "height="
for /f "tokens=1*delims=:" %%b in ('"MEDIAINFO --INFORM=Image;%%Width%%:%%Height%% "%%~a""') do (
echo(%%~a 1 1 1 %%~b %%~c
)
))>infofile.txt
type infofile.txt
output example:
C:\Users\Private\Pictures\snap001.png 1 1 1 528 384
C:\Users\Private\Pictures\snap002.png 1 1 1 1920 1080
C:\Users\Private\Pictures\snap003.png 1 1 1 617 316
C:\Users\Private\Pictures\snap004.png 1 1 1 1920 1080
C:\Users\Private\Pictures\snap005.png 1 1 1 514 346
C:\Users\Private\Pictures\snap006.png 1 1 1 1920 1080
C:\Users\Private\Pictures\snap007.png 1 1 1 395 429
C:\Users\Private\Pictures\snap008.png 1 1 1 768 566
C:\Users\Private\Pictures\snap009.png 1 1 1 1536 1080
C:\Users\Private\Pictures\snap010.png 1 1 1 1600 480
Here's a tooltipInfo.bat (jscript\bat hybrid that can be used as a .bat) that takes the tooptip information for a file and does not require any external software:
#if (#X)==(#Y) #end /* JScript comment
#echo off
rem :: the first argument is the script name as it will be used for proper help message
cscript //E:JScript //nologo "%~f0" %*
exit /b %errorlevel%
#if (#X)==(#Y) #end JScript comment */
//////
FSOObj = new ActiveXObject("Scripting.FileSystemObject");
var ARGS = WScript.Arguments;
if (ARGS.Length < 1 ) {
WScript.Echo("No file passed");
WScript.Quit(1);
}
var filename=ARGS.Item(0);
var objShell=new ActiveXObject("Shell.Application");
/////
//fso
ExistsItem = function (path) {
return FSOObj.FolderExists(path)||FSOObj.FileExists(path);
}
getFullPath = function (path) {
return FSOObj.GetAbsolutePathName(path);
}
//
//paths
getParent = function(path){
var splitted=path.split("\\");
var result="";
for (var s=0;s<splitted.length-1;s++){
if (s==0) {
result=splitted[s];
} else {
result=result+"\\"+splitted[s];
}
}
return result;
}
getName = function(path){
var splitted=path.split("\\");
return splitted[splitted.length-1];
}
//
function main(){
if (!ExistsItem(filename)) {
WScript.Echo(filename + " does not exist");
WScript.Quit(2);
}
var fullFilename=getFullPath(filename);
var namespace=getParent(fullFilename);
var name=getName(fullFilename);
var objFolder=objShell.NameSpace(namespace);
var objItem=objFolder.ParseName(name);
//https://msdn.microsoft.com/en-us/library/windows/desktop/bb787870(v=vs.85).aspx
WScript.Echo(fullFilename + " : ");
WScript.Echo(objFolder.GetDetailsOf(objItem,-1));
}
main();
Output if used against a picture:
C:\TEST.PNG :
Item type: PNG image
Dimensions: ?871 x 836?
Size: 63.8 KB
so you can:
for /f "delims=? tokens=2" %%a in ('toolTipInfo.bat C:\TEST.PNG ^|find "Dimensions:"') do echo %%a
EDIT:
Another way with WIA.ImageFile object - imgInfo.bat
I'm not sure whether you will be able to get at file properties like that in a batch script. I would recommend using something like Python. Here is a link to another thread which suggests using the PIL.imaging library for this.
If you are interested in perusing this route but do not know any Python let me know and I can put a quick script together for this.
Instructions to install Python
As discussed you will need to install Python for this to run. I have also found out that PIL is a third party library, so you will also need to download and install this (make sure you pick the same version as your python installation e.g. if you have installed Python 2.7 on 64 bit, you would need "Pillow-2.1.0.win-amd64-py2.7.exe" from here).
Once you have done the install you can check that this is working by opening the command prompt (cmd) and entering c:\python27\python.exe (if you add c:\python27 top your PATH environment variable you will just need to type "Python"). This will open the python command prompt. Type print "test" and you should see thr output printed then exit().
Once Python is installed you can create a script. Here is some code that will do what you have requested (list all files of a given extension that are found from a base path with 1 1 1 width height to a file).
Open a text editor e.g. notepad paste in the code below and save as "image_attr.py" or whatever name you decide to use:
from PIL import Image
import os, sys
def main():
# if a cmd line arg has been passed in use as base path...
if len(sys.argv) > 1:
base_path = sys.argv[1]
# else use current working dir...
else:
base_path = os.getcwd()
# image file extensions to be included, add or remove as required...
ext_list = ['.bmp', '.jpg']
# open output file...
outfile = os.path.join(base_path,'infofile.txt')
file_obj = open(outfile, 'wb')
# walk directory structure...
for root, dirs, files in os.walk(base_path):
for f in files:
# check of file extension is in list specified above...
if os.path.splitext(f)[1].lower() in ext_list:
f_path = os.path.join(root, f)
width, height = Image.open(f_path).size
output = f_path + ' 1 1 1 ' + str(width) + ' ' + str(height) +'\r\n'
file_obj.write(output)
file_obj.close()
if __name__ == '__main__':
main()
Save this and remember the path to the file, I will use c:\python27\image_attr.py for this example. You can then call this from cmd or from a batch script passing in an arguement for the base path e.g.:
python c:\python27\image_attr.py E:\Users\Prosserc\Pictures
Please note that any arguements with spaces in them should be enclosed with double quotes.
Please let me know if you have any questions.
EDIT
For Python 3 the amendments should be minimal in theory. In this case I am writing the output the the screen rather than a file, but redirecting to a file from cmd:
from PIL import Image
import os, sys
def main():
# if a cmd line arg has been passed in use as base path...
if len(sys.argv) > 1:
base_path = sys.argv[1]
# else use current working dir...
else:
base_path = os.getcwd()
# image file extensions to be included, add or remove as required...
ext_list = ['.bmp', '.jpg']
# walk directory structure
for root, dirs, files in os.walk(base_path):
for f in files:
# check of file extension is in list specified above...
if os.path.splitext(f)[1].lower() in ext_list:
f_path = os.path.join(root, f)
width, height = Image.open(f_path).size
output = f_path + ' 1 1 1 ' + str(width) + ' ' + str(height) +'\r\n'
print(output)
if __name__ == '__main__':
main()
Call with:
python c:\python27\image_attr.py E:\Users\Prosserc\Pictures > infofile.txt
The code below is based on tooltipInfo.bat by npocmaka except that I used ExtendedProperty() instead of GetDetailsOf().
#if (#X==#Y) #then
:: Batch
#echo off & setLocal enableExtensions disableDelayedExpansion
(call;) %= sets errorLevel to 0 =%
(
for /f "tokens=1,2 delims=x " %%X in ('
cscript //E:JScript //nologo "%~dpf0" "%~dpf1" %2
') do (set "width=%%X" & set "height=%%Y") %= for /f =%
) || goto end %= cond exec =%
echo("%~nx1": width=%width% height=%height%
:end - exit program with appropriate errorLevel
endLocal & goto :EOF
#end // JScript
// objects
var FSOObj = WScript.CreateObject("Scripting.FileSystemObject"),
objShell = WScript.CreateObject("Shell.Application");
var ARGS = WScript.Arguments;
if (ARGS.length != 1) {
WScript.StdErr.WriteLine("too many arguments");
WScript.Quit(1);
} else if (ARGS.Item(0) == "") {
WScript.StdErr.WriteLine("filename expected");
WScript.Quit(1);
} // if
ExistsItem = function (path) {
return FSOObj.FolderExists(path) || FSOObj.FileExists(path);
} // ExistsItem
getFullPath = function (path) {
return FSOObj.GetAbsolutePathName(path);
} // getFullPath
getParent = function(path) {
var splitted = path.split("\\"), result = "";
for (var s=0; s<splitted.length-1; s++) {
if (s == 0) {
result = splitted[s];
} else {
result = result + "\\" + splitted[s];
} // if
} // for
return result;
} // getParent
getName = function(path) {
var splitted = path.split("\\");
return splitted[splitted.length-1];
} // getName
var filename = ARGS.Item(0),
shortFilename = filename.replace(/^.+\\/, '');
if (!ExistsItem(filename)) {
WScript.StdErr.WriteLine('"' + shortFilename + '" does not exist');
WScript.Quit(1);
} // if
var fullFilename=getFullPath(filename), namespace=getParent(fullFilename),
name=getName(fullFilename), objFolder=objShell.NameSpace(namespace),
objItem;
if (objFolder != null) {
objItem=objFolder.ParseName(name);
if (objItem.ExtendedProperty("Dimensions") != null) {
WScript.Echo(objItem.ExtendedProperty("Dimensions").slice(1, -1));
} else {
WScript.StdErr.WriteLine('"' + shortFilename +
'" is not an image file');
WScript.Quit(1);
} // if 2
} // if 1
WScript.Quit(0);
This can be done with PowerShell with the Wia.ImageFile
break>infofile.txt
$image = New-Object -ComObject Wia.ImageFile
dir . -recurse -include *.jpg, *.gif, *.png, *.bmp | foreach{
$fname =$_.FullName
$image.LoadFile($fname)
echo ($fname -replace "\\","/" 1 1 1 $image.Width $image.Height)>>infofile.txt
}
The benifit is most windows computers have powershell instaled
It seams slower than CMD/batch scripts
That said CMD/batch scripts can't do this as far as I know.
Install imagemagick, then use the following inside a batch file:
FOR /F "tokens=* USEBACKQ" %%F IN (`magick identify -format "%%wx%%h" %1`) DO (SET dimensions=%%F)
#ECHO result: %dimensions%

Accept parameters from a .Net console app into a Batch file

I am trying to pass parameters from a .Net console app to a batch file. The parameters are not coming into the batch file.
How can I properly set up passing the parameters into the bat file?
Here is the method in the console app that I'm executing.
private static int ProcessBatFile(string ifldr, string ofldr, string iext, string oext, Int16 filewidth, Int16 fileheight, Int16 ctr)
{
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = ConfigurationSettings.AppSettings.Get("BatProcessDir") + "imagemagick.bat";
psi.Arguments = "-ifldr=" + ifldr + " -ofldr=" + ofldr + " -iext=" + iext + " -oext=" + oext + " -iwid=" + filewidth + " -ihgt=" + fileheight;
psi.UseShellExecute = false;
Process process = new Process();
process.StartInfo = psi;
process.Start();
return ctr;
}
Below, is the code in the bat file I'm trying to execute:
#echo on
echo %ofldr%
echo %ifldr%
echo %iwid%
echo %ihgt%
echo %oext%
echo %iext%
If you pass them as paramters, you can do this in the c# code:
psi.Arguments = ifldr + " " + ofldr + " " + iext + " " + oext + " " + filewidth + " " + fileheight;
and do this in the batch file:
#echo on
set ifldr=%1
set ofldr=%2
set iext=%3
set oext=%4
set iwid=%5
set ihgt=%6
echo %ofldr%
echo %ifldr%
echo %iwid%
echo %ihgt%
echo %oext%
echo %iext%
As an alternative solution, you can also directly modify the environment before executing the batch file using System.Environment.SetEnvironmentVariable:
System.Environment.SetEnvironmentVariable ("ifldr", ifldr);
....
This causes less problems if the parameters may contain spaces.

Resources