Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the file name without extension in a Windows Batch Script

I'm trying to create a right-click context menu command for compressing JavaScript files with YUI compressor. My ultimate goal is to try to get this to run on a context menu:

java.exe -jar yuicompressor-2.4.2.jar -o <filename>.min.js <filename>.js 

I know I can use the variable %1 to reference the file name being opened. I can't figure out how to get this command into a batch file syntax and haven't been able to find any answers online.

Update:
Jeremy's answer (+comments) worked. For anyone who stumbles upon this, here is what I had to do:

In the action I created for the JavaScript file, I used this as the command:

minify.bat "%1" 

Which calls my batch script, which looks like this:

java.exe -jar yuicompressor-2.4.2.jar -o "%~dpn1.min.js" %1 

For the batch script, keep in mind that the code above assumes the directories for java.exe & yuicompressor are both added to your PATH variables. If you don't add these to your path, you'll have to use the full path for the files.

The sequence %~dpn is used to get:

  1. %~d - The drive
  2. %~p - The path
  3. %~n - The file name
like image 841
Dan Herbert Avatar asked Sep 24 '09 14:09

Dan Herbert


People also ask

How do you get the name of a file without the extension?

GetFileNameWithoutExtension(ReadOnlySpan<Char>) Returns the file name without the extension of a file path that is represented by a read-only character span.

Is the filename extension for DOS batch files?

When a batch file is run, the shell program (usually COMMAND.COM or cmd.exe) reads the file and executes its commands, normally line-by-line. Unix-like operating systems, such as Linux, have a similar, but more flexible, type of file called a shell script. The filename extension . bat is used in DOS and Windows.

What does 0 |% 0 Do in batch?

What it is: %0|%0 is a fork bomb. It will spawn another process using a pipe | which runs a copy of the same program asynchronously. This hogs the CPU and memory, slowing down the system to a near-halt (or even crash the system).

What is %% f in batch file?

For simple batch files, a single character such as %%f will work. You can use multiple values for variable in complex batch files to distinguish different replaceable variables.


1 Answers

Change the action to call a batch file:

RunCompressor.bat "%1" 

Use %~n1 to get the filename without the extension in RunCompressor.bat:

start javaw.exe -jar yuicompressor-2.4.2.jar -o "%~n1.min.js" "%1" 

Helpful article

start javaw.exe closes the command window when running the batch file.

like image 158
Jeremy Stein Avatar answered Sep 23 '22 02:09

Jeremy Stein