8

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?

11

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

  • Right - %~n1 and %~x1 is the missing sauce, thank you. – Justicle Oct 5 '16 at 21:59

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.