Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string symbol manipulation in batch files?

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?

like image 765
Brian R. Bondy Avatar asked Apr 19 '26 16:04

Brian R. Bondy


1 Answers

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"
  • BatchFiles Website (kind advanced)
  • Decent forum post
  • Another Good Post
like image 134
Andrew Avatar answered Apr 21 '26 11:04

Andrew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!