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?

Justicle
  • 496

1 Answers1

35

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

DavidPostill
  • 162,382