批处理脚本 - 对目录中的每个文件运行命令 [英] batch script - run command on each file in directory

查看:37
本文介绍了批处理脚本 - 对目录中的每个文件运行命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一些 xls 文件转换为 xlsx 文件.通过在 cmd 提示符(windows)中运行此命令,我可以成功地将一个 xls 文件转换为 xlsx:

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 是 Gnumeric 的命令行实用程序,可以在不同的电子表格文件格式之间进行转换)

(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

输出应该是

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

有人可以帮我吗?

推荐答案

for /r %%v in (*.xls) do ssconvert "%%v" "%%vx"

有人让我解释这一点,所以:

a couple have people have asked me to explain this, so:

第 1 部分:for/r %%v in (*.xls)

这部分返回当前目录中具有 xls 扩展名的文件数组.%% 可能看起来有点奇怪.这基本上是 %PATH% 或 %TEMP% 中使用的命令行中的特殊 % 字符.要在批处理文件中使用它,我们需要像这样转义它:%%PATH%%%%TEMP%%.在这种情况下,我们只是转义临时变量 v,它将保存我们的文件名数组.

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.

我们使用 /r 开关来递归搜​​索文件,因此也将定位子文件夹中的任何匹配文件.

We are using the /r switch to search for files recursively, so any matching files in child folders will also be located.

第二部分: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

将执行以下命令:

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"

这篇关于批处理脚本 - 对目录中的每个文件运行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆