首页 文章

批处理:删除文件扩展名

提问于
浏览
125

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

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

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

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

5 回答

  • 13

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

    如果您的变量保存的文件实际上不存在,则 FOR 方法将不起作用 . 如果你知道扩展的长度,你可以使用的一个技巧是采用子字符串:

    %var:~0,-4%
    

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

  • 8

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

    echo %%~nf
    
  • 252

    这是一个非常晚的响应,但我想出了解决我在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
    
  • 26

    我正在使用这个,如果我只是想从变量中剥离扩展(不循环任何目录或现有文件):

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

    如果要从完整路径中剥离扩展名,请改为使用 %%dpnf

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

    Example:

    (编写 % 而不是 %% ,直接在控制台中使用它,而不是在脚本中 . )

    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
    

相关问题