Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

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

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:directoryfile1.xls
c:directoryfile2.xls
c:directoryfile3.xls

the output should be

c:directoryfile1.xlsx
c:directoryfile2.xlsx
c:directoryfile3.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?

question from:https://stackoverflow.com/questions/14237548/batch-script-run-command-on-each-file-in-directory

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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:empmySheet.xls, c:empmySheet_yesterday.xls, c:empmySheet_20160902.xls

the following commands would be executed:

ssconvert "c:empmySheet.xls" "c:empmySheet.xlsx" ssconvert "c:empmySheet_yesterday.xls" "c:empmySheet_yesterday.xlsx" ssconvert "c:empmySheet_20160902.xls" "c:empmySheet_20160902.xlsx"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...