20

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 1

33

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
  • Right - %~n1 and %~x1 is the missing sauce, thank you.
    – Justicle
    Commented Oct 5, 2016 at 21:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .