I have the following batch script from Wikipedia:
@echo off
for /R "C:\Users\Admin\Ordner" %%f in (*.flv) do (
echo %%f
)
pause
In the for-loop all files with the extension flv get echoed, but I want the make some actions with the file(s) where I need one time the file without the extension and one time with the extension. How could I get these two?
I searched for solutions but I don't find one. I'm a real newbie in batch...
This question is related to
file
batch-file
Without looping
I am using this if I simply want to strip the extension from a filename or variable (without listing any directories or existing files):
for %%f in ("%filename%") do set filename=%%~nf
If you want to strip the extension from a full path, use %%dpnf
instead:
for %%f in ("%path%") do set path=%%~dpnf
Example:
(Use directly in the console)
@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
Using cygwin bash to do the chopping
:: 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
I'm also a stranger to windows cmd, but try this:
echo %%~nf
In case the file your variable holds doesn't actually exist the FOR
approach won't work. One trick you could use, if you know the length of the extension, is taking a substring:
%var:~0,-4%
the -4
means that the last 4 digits (presumably .ext) will be truncated.
This is a really late response, but I came up with this to solve a particular problem I had with DiskInternals LinuxReader appending '.efs_ntfs' to files that it saved to non-NTFS (FAT32) directories :
@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
If your variable is an argument, you can simply use %~dpn
(for paths) or %~n
(for names only) followed by the argument number, so you don't have to worry for varying extension lengths.
For instance %~dpn0
will return the path of the batch file without its extension, %~dpn1
will be %1
without extension, etc.
Whereas %~n0
will return the name of the batch file without its extension, %~n1
will be %1
without path and extension, etc.
Source: Stackoverflow.com