How to extract extension of input file parameter using Windows batch script

Given this batch script - how do I isolate filename and extension, like in the output given:

@echo off
REM usage split.bat <filename>
set input_file="%1"
echo input file name is <filename> and extension is <extension>
c:\split.bat testfile.txt
input filename is testfile and extension is txt

That is - what's the correct syntax for <filename> and <extension> in this code?

1 Answer

How do I isolate filename and extension from %1?

Use the following batch file (split.bat):

@echo off
setlocal
REM usage split.bat <filename>
set _filename=%~n1
set _extension=%~x1
echo input file name is ^<%_filename%^> and extension is ^<%_extension%^>
endlocal 

Notes:

  • %~n1 - Expand %1 to a file Name without file extension.

  • %~x1 - Expand %1 to a file eXtension only.

  • < and > are special characters (redirection) and must be escaped using ^.

Example usage:

> split testfile.txt
input file name is <testfile> and extension is <.txt>

Further Reading

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like