It is possible to use a string substitution to delete everything left to $
and the first dollar sign from line and get just everything after $
into an environment variable if the entire line contains only a single $
.
@echo off
if exist test.txt (
set "Line="
set /P Line=<test.txt
if defined Line goto ProcessLine
)
set "Line=50-A Description of the item $23"
:ProcessLine
echo on
set "Value=%Line:*$=%"
@echo off
echo Value after first $ is: %Value%
set "Value="
set "Line="
This batch code reads the first line of file test.txt
via input redirection and assigns it to environment variable Line
if the file test.txt
exists in current directory with the posted example line. Otherwise the environment variable Line
is defined with the example text for demonstrating this method.
Line 10 makes the string substitution removing the first $
and everything left to it. Help of command SET output on running set /?
in a command prompt window explains this string substitution briefly.
The value of an environment variable is usually referenced with %VariableName%
which results in being replaced during preprocessing state of the command line by current value of the referenced environment variable before executing the command line.
A string substitution is specified with colon :
after variable name. The asterisk *
after the colon informs the Windows command interpreter that everything up to and including first occurrence of searched string specified next up to equal sign =
should be replaced by the string after equal sign up to percent sign %
indicating end of replace string and additionally the string substitution.
In this case the search string is just the character $
and the replace string is an empty string.
The batch file turns on echo mode temporarily to display that the entire string substitution is done here by Windows command interpreter cmd.exe
executing the batch file already during preprocessing the line before executing the command line which is for this example:
set "Value=23"
The next line after turning off echo mode again outputs:
Value after first $ is: 23
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
echo /?
goto /?
if /?
set /?
Read also the Microsoft article about Using Command Redirection Operators for an explanation of redirection operator <
.