加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

Windows批处理脚本 – 将文件名读入变量

发布时间:2020-12-14 05:44:35 所属栏目:Windows 来源:网络整理
导读:我试图逐个转换目录中的文件(电影).每个新转换的文件都需要分配一个新文件名 – 旧文件名具有新扩展名. 我已经尝试过以下内容来阅读源文件,剥离扩展并分配一个新文件: @echo offsetlocal DisableDelayedExpansioncd target_dirfor %%x in (*) do ( echo %%
我试图逐个转换目录中的文件(电影).每个新转换的文件都需要分配一个新文件名 – 旧文件名具有新扩展名.

我已经尝试过以下内容来阅读源文件,剥离扩展并分配一个新文件:

@echo off
setlocal DisableDelayedExpansion
cd target_dir
for %%x in (*) do (
  echo %%x
  set source=%%x
  echo Source #%source%#
  set target=%source:.mpg=%
  echo Target #%target%#
  transcode %source% %target%.mp4
)

不幸的是,这不起作用.如输出所示,我甚至无法将当前文件复制到变量“source”中:

E:target_dir>..test.bat
movie1.mpg
source ##
target ##
movie2.mpg
source ##
target ##

我用Google搜索并认为我已找到正确的语法,但这似乎不是它.谢谢你的帮助!

解决方法

jlahd显示正确的解决方案,而不将文件名复制到变量.

但我想解释你目前的问题.

As the output shows,I am not even managing to copy the current file
into the variable “source”:

你找到了BBB(批量初学者bug),实际上你设置了变量,但是你以后无法访问内容.

这是批处理解析器使用代码块的效果,因为这些块被解析并且在执行代码之前将完成百分比扩展.
代码块是括号内的代码或由&,&&连接的命令.或||.

为了避免这个问题,引入了延迟扩展.
然后你就可以使用!变量了!在运行时扩展变量.

setlocal EnableDelayedExpansion
cd target_dir
for %%x in (*) do (
  echo %%x
  set source=%%x
  echo Source #!source!#
  set target=!source:.mpg=!
  echo Target #!target!#
  transcode !source! !target!.mp4
)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读