批处理:删除文件扩展名

时间:2010-07-09 18:29:45

标签: file batch-file

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

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

在for循环中,所有扩展名为flv的文件都会被回显, 但是我希望用文件做一些动作 我需要一次没有扩展名的文件和一次扩展名的文件。 我怎么能得到这两个?

我搜索了解决方案,但我找不到。 我是一个真正的新手......

7 个答案:

答案 0 :(得分:276)

您可以使用%%~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.    

答案 1 :(得分:26)

如果您的变量保存的文件确实存在,则FOR方法无法正常工作。如果你知道扩展的长度,你可以使用的一个技巧是使用子字符串:

%var:~0,-4%

-4表示最后4位数(可能是 .ext )将被截断。

答案 2 :(得分:13)

我也是Windows cmd的陌生人,但试试这个:

echo %%~nf

答案 3 :(得分:8)

这是一个非常晚的响应,但我想出了解决我在DiskInternals LinuxReader附加'.efs_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

答案 4 :(得分:2)

如果变量是一个参数,则可以简单地使用%~dpn后跟参数编号,因此您不必担心扩展名长度的变化。

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

答案 5 :(得分:1)

如果我只是想从变量中删除扩展名(而不循环任何目录或现有文件),我就使用此方法:

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 %~nf

REM ===========
REM OUTPUT:
REM file name
REM C:\Dir\file

答案 6 :(得分:0)

使用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
相关问题