2010-07-09 171 views
112

我已经从维基百科以下批处理脚本:批次:删除文件扩展名

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

在for循环扩展名为FLV的所有文件得到呼应, 但我想做些动作与文件( s) 其中我需要一次没有扩展名的文件和一次扩展名。 我怎么能得到这两个?

我搜索的解决方案,但我没有找到一个。 我在一批真正的新手...

回答

221

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

伟大的工作。它帮助了我。 – 2017-07-20 15:57:21

+2

只是一个简短的提示:在上面的例子中** %% f **会像'C:\ Users \ Admin \ Ordner \ foo.flv'和** %%〜nf **会给你'foo' 。如果你想要一切_except_扩展使用** %%〜df %%〜pf %%〜nf **这会给你'C:\ Users \ Admin \ Ordner \ foo' – ehambright 2017-08-02 22:05:10

13

我也是一个陌生人到CMD窗口,但试试这个:

echo %%~nf 
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 
+0

我不确定它会回答问问题,但它实际上帮助了我,谢谢! – matan7890 2014-08-06 23:42:56

+1

@ matan7890真;该操作并未指定“我想要对文件进行一些操作”[原文如此],但其中一项操作可能会重命名它们,在这种情况下,我的答案是对已接受答案的扩展。 – 2014-08-07 06:29:44

+0

这帮助了我的一位朋友,他打开了一个附件,并在他的所有文件中加入了“.encrypted”以及赎金要求。显然,攻击脚本必须是与此相反的批处理文件,并将'.encrypted'添加到所有文件。 – AwokeKnowing 2016-03-22 19:13:38

23

如果变量所保存的文件实际上不存在,则FOR方法将不起作用。你可以使用,如果你知道扩展的长度,一招走一个子:

%var:~0,-4% 

-4意味着最后4个位数(大概.EXT)将被截断。

+0

这不适用于我(在Win8.1) - 也许我误会了尝试'echo%f:〜0,-4% '在问题中使用的例子的背景下。我究竟做错了什么? – Wolf 2015-11-23 14:24:45

+2

显然,这适用于“正常”变量,而不是FOR变量(或者我只是不知道正确的语法)。无论如何,这将在OP示例中起作用:'SET fl = %% f'然后'echo%fl:〜0,-4%' – 2015-11-23 14:46:42

+1

适用于Win10中的简单命令行参数,如%1,% 2等。谢谢! – deko 2016-10-24 07:36:13

0

如何删除多个扩展名? 可以说我的文件的扩展名是filename.abc.def.xyz.anything,我只想提取文件名。