views:

6262

answers:

7

Is there a way to take substrings of a string with .bat/.cmd files?

For example given the string "hello.txt" is there a way to strip the .txt?

EDIT: Also is there a more general way to do this, not under the assumption that it is a file name or file path?

+6  A: 

If this is a file passed as a parameter, you can use %~n1, like this:

test.bat
----------
echo %~n1 %~n2

c:\> test.bat myfile.txt my.long.file.bat
  myfile my.long.file

If you know the length of the string you can use the substring operator:

echo %variable:0,4%   =>  "test.txt" => "test"

And to get everything EXCEPT the last 4 characters:

echo %variable:~0,-4%  => "file...name.txt" => "file...name"
Andrew Backer
I found the "BatchFiles Website" link very helpful. It has samples for many common tasks. It has good but short descriptions of each at the top, so you don't have to scroll through a page of scripts interspersed with descriptions to find if there's a sample of what you need.
Adam Porad
BatchFiles is gone with GeoCities. Here's archive.org's version: http://web.archive.org/web/20080611141151/http://www.batchfiles.co.nr/Not that it matters much - the web site says that it's for Win98 only and that it won't apply to NT.
Scott Bilas
A: 

For an arbitrary string, I don't think so.

For this very example, %~n1 will resolve to a name without extension.

GSerg
+1  A: 

The general substring syntax in .cmd files (and .bat files post Win95) is:

%variable:~num_chars_to_skip,num_chars_to_keep%

This page provides more options: VarSubstring

Chris Noe
+1  A: 

Try help set for some string processing available for cmd.exe. The help for set includes things you can do normally, outside the 'set' command

You can do things like

set source=hello.txt
REM print hello
echo %source:~0,-4%
REM print o.t
echo %source:~4,3%
REM print help.txt
echo %source:lo=p%
REM etc
echo %source:llo=%

There may be somethings wrong in the 'code' above. I'm writing it from memory, without a cmd.exe available near me to test.

pmg
+2  A: 

For substring and other interesting "variable substitution" methods you can get help with:

set /?

For string parsing (e.g. finding a '.' in a string) try

for /?

Denes Tarjan
+1  A: 

Best way is just to install python (or perl) Believe me, I've tried almost everything, and it's just headache to do text manipulation in 'DOS' (or actually anything else).

Noam
A: 

You can also look at the documentation for call (call /?) for getting file and directory-based specific substring info as well.