2010-07-09 163 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,我只想提取文件名。