批处理: 删除文件扩展名

我有以下来自维基百科的批处理脚本:

@echo off
for /R "C:\Users\Admin\Ordner" %%f in (*.flv) do (
echo %%f
)
pause

在 for-loop 中,所有扩展名为 flv 的文件都会得到回显, 但是我希望对文件进行一些操作 我需要一次没有扩展名的文件和一次有扩展名的文件。 我怎么才能得到这两个?

我试图寻找解决办法,但是一无所获。 我是一批真正的新手..。

251882 次浏览

我对 windows cmd 也是一个陌生人,但是试试这个:

echo %%~nf

您可以使用 %%~nf来获取文件名,只需按照 for的参考文献中的描述:

@echo off
for /R "C:\Users\Admin\Ordner" %%f in (*.flv) do (
echo %%~nf
)
pause

以下备选方案可供选择:

Variable with modifier  Description


%~I                     Expands %I which removes any surrounding
quotation marks ("").
%~fI                    Expands %I to a fully qualified path name.
%~dI                    Expands %I to a drive letter only.
%~pI                    Expands %I to a path only.
%~nI                    Expands %I to a file name only.
%~xI                    Expands %I to a file extension only.
%~sI                    Expands path to contain short names only.
%~aI                    Expands %I to the file attributes of file.
%~tI                    Expands %I to the date and time of file.
%~zI                    Expands %I to the size of file.
%~$PATH:I               Searches the directories listed in the PATH environment
variable and expands %I to the fully qualified name of
the first one found. If the environment variable name is
not defined or the file is not found by the search,
this modifier expands to the empty string.

这是一个非常晚的响应,但是我想出这个来解决我在 DiskInternals LinuxReader 附加’时遇到的一个特殊问题。Fs _ ntfs’保存到非 NTFS (FAT32)目录的文件:

@echo off
REM %1 is the directory to recurse through and %2 is the file extension to remove
for /R "%1" %%f in (*.%2) do (
REM Path (sans drive) is given by %%~pf ; drive is given by %%~df
REM file name (sans ext) is given by %%~nf ; to 'rename' files, move them
copy "%%~df%%~pf%%~nf.%2" "%%~df%%~pf%%~nf"
echo "%%~df%%~pf%%~nf.%2" copied to "%%~df%%~pf%%~nf"
echo.
)
pause

如果您的变量持有的文件实际上不存在,那么 FOR方法将不起作用。如果你知道扩展名的长度,你可以使用一个技巧,那就是获取一个子字符串:

%var:~0,-4%

-4表示最后4位数字(大概是 。下一页)将被截断。

没有循环

如果我只是想从文件名或变量中去除扩展名(不列出任何目录或现有文件) ,我就会使用这种方法:

for %%f in ("%filename%") do set filename=%%~nf

如果要从完整路径中去除扩展名,请改用 %%dpnf:

for %%f in ("%path%") do set path=%%~dpnf

例如:

(直接在控制台中使用)

@for %f in ("file name.dat") do @echo %~nf
@for %f in ("C:\Dir\file.dat") do @echo %~dpnf


OUTPUT:


file name
C:\Dir\file

用 Cygwin Bash 来切菜

  :: e.g. FILE=basename.mp4 => FILE_NO_EXT=basename
set FILE=%1
for /f "delims=" %%a in ('bash -c "FILE=%FILE%; echo ${FILE/.*/}" ') do set FILE_NO_EXT=%%a

如果您的变量是一个参数,您可以简单地使用 %~dpn(用于路径)或 %~n(仅用于名称)后跟参数号,这样您就不必担心可变的扩展长度。

例如,%~dpn0将返回没有扩展名的批处理文件的路径,%~dpn1将返回没有扩展名的 %1,等等。

%~n0将返回没有扩展名的批处理文件的名称,而 %~n1将是没有路径和扩展名等的 %1

完整的东西是 %~dpfn0,当你仔细观察的时候,它开始有意义了:

  • D Drive
  • P Path
  • N Name
  • X 是 eX张力,
  • Fn 是带扩展名的 FileName