如何使用 Windows 批处理脚本提取输入文件参数的扩展名

Jus*_*cle 13 windows batch

鉴于此批处理脚本 - 我如何隔离文件名和扩展名,就像在给定的输出中一样:

@echo off
REM usage split.bat <filename>
set input_file="%1"
echo input file name is <filename> and extension is <extension>

c:\split.bat testfile.txt
input filename is testfile and extension is txt
Run Code Online (Sandbox Code Playgroud)

那就是 -<filename> and <extension>这段代码中正确的语法是什么?

Dav*_*ill 19

如何隔离文件名和扩展名%1

使用以下批处理文件 (split.bat):

@echo off 
setlocal
REM usage split.bat <filename>
set _filename=%~n1
set _extension=%~x1
echo input file name is ^<%_filename%^> and extension is ^<%_extension%^>
endlocal  
Run Code Online (Sandbox Code Playgroud)

笔记:

  • %~n1- 扩展%1为没有文件扩展名的文件名。

  • %~x1-%1仅扩展到文件扩展名。

  • <>特殊字符(重定向),必须转义使用^

用法示例:

> split testfile.txt
input file name is <testfile> and extension is <.txt>
Run Code Online (Sandbox Code Playgroud)

进一步阅读