string symbol manipulation in batch files?
-
05-07-2019 - |
Question
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?
Solution
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"
OTHER TIPS
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
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 /?
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.
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).
For an arbitrary string, I don't think so.
For this very example, %~n1
will resolve to a name without extension.
You can also look at the documentation for call (call /?) for getting file and directory-based specific substring info as well.