Here is a method that applies the sometimes so-called code injection technique:
@echo off
setlocal EnableExtensions EnableDelayedExpansion
rem // Define (non-empty) input string here:
set "name=text4_text5_text6_text7_2000-01-02"
rem // Clear variables:
set "rest=" & set "last="
rem // Split off the last `_`-separated item using the code injection technique:
set "rest=%name:_=" & (if defined last set "rest=!rest!_!last!") & set "last=%"
rem // Return result:
set name
set rest
set last
endlocal
pause
The related console output is going to be the following:
name=text4_text5_text6_text7_2000-01-02
rest=text4_text5_text6_text7
last=2000-01-02
To find out how it works change @echo off
to @echo on
and check the console output. This method is based on sub-string substitution, and it requires delayed variable expansion.
Regard, that this approach will fail with a string that contains !
, ^
and "
.
Notice, that multiple consecutive separators become collapsed into one, so a string like abc__def__01
would be split into abc_def
and 01
. To avoid that and thus retain the separators, change the core code to this:
rem // Clear variables:
set "rest=" & set "last=" & set "flag="
rem // Split off the last `_`-separated item using the code injection technique:
set "rest=%name:_=" & (if defined flag (set "rest=!rest!_!last!") else set "flag=#") & set "last=%"
For more information about this method refer to split string into substrings based on delimiter [DosTips].