Por*_*oru 145 file batch-file
我有来自维基百科的以下批处理脚本:
@echo off
for /R "C:\Users\Admin\Ordner" %%f in (*.flv) do (
echo %%f
)
pause
Run Code Online (Sandbox Code Playgroud)
在for循环中,所有扩展名为flv的文件都会被回显,但是我希望对文件进行一些操作,其中我需要一次没有扩展名的文件和一次使用扩展名的文件.我怎么能得到这两个?
我搜索了解决方案,但我找不到.我是一个真正的新手批...
Dir*_*mar 291
您可以使用%%~nf仅按参考中所述获取文件名for:
@echo off
for /R "C:\Users\Admin\Ordner" %%f in (*.flv) do (
echo %%~nf
)
pause
Run Code Online (Sandbox Code Playgroud)
可以使用以下选项:
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.
Oha*_*der 26
如果您的变量保存的文件实际上不存在,则该FOR方法将不起作用.如果你知道扩展的长度,你可以使用的一个技巧是采用子字符串:
%var:~0,-4%
Run Code Online (Sandbox Code Playgroud)
这-4意味着最后4位数(可能是.ext)将被截断.
mod*_*diX 10
如果您的变量是一个参数,您可以简单地使用%~dpn(对于路径) 或%~n(仅对于名称) 后跟参数编号,这样您就不必担心不同的扩展长度。
例如%~dpn0将返回不带扩展名的批处理文件的路径,%~dpn1将%1不带扩展名等。
而%~n0将返回不带扩展名的批处理文件的名称,%~n1将%1不带路径和扩展名等。
当你仔细观察时,整个事情%~dpfn0就开始有意义了:
这是一个非常晚的响应,但我想出了解决我在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
Run Code Online (Sandbox Code Playgroud)
不循环
如果我只是想从文件名或变量中删除扩展名(不列出任何目录或现有文件),我会使用它:
for %%f in ("%filename%") do set filename=%%~nf
Run Code Online (Sandbox Code Playgroud)
如果要从完整路径中删除扩展名,请%%dpnf改用:
for %%f in ("%path%") do set path=%%~dpnf
Run Code Online (Sandbox Code Playgroud)
例子:
(直接在控制台使用)
@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
Run Code Online (Sandbox Code Playgroud)