I am writing a short batch script which attempts to take the first line of text file and remove the trailing backslash if present. This will then repeat for the remaining lines of the input file. However, when I run the script the line does not remove the backslash. My guess is this is a simple fix, but I have tried several troubleshooting methods with no luck. The code is posted below for reference. Thanks!
@echo on
setLocal EnableDelayedExpansion
::set firstline to firstline of test.txt
set /p firstline=<test.txt
::Remove trailing slash if present
IF !firstline:~-1!==\ SET firstline=!firstline:~0,-1!
::Output firstline (without \ to new txt file)
echo !firstline!>test2.txt
endlocal
test.txt file:
C:\Desktop\example\path\
C:\Desktop\example\path\2\
C:\Desktop\example\path\test\
You are correct that it's a simple problem. In fact it is solved with the introduction of 4 characters, all the same one.
Exposing a backslash in batch is a bad idea, it's likely to confuse the interpreter into thinking that it's dealing with an actual file or path. You should surround it with double-quotes. This is true with other characters, including !%&*?/\<>,. mostly special characters that deal with paths and files. There may be more, and some are only occasionally a problem. Even 1 and 2 can cause trouble when next to a redirection character.
Just to let you know, neither setlocal
or the delayed expansion notation !
are necessary here, although there is no harm in it. (Except that the delayed notation makes debugging harder as it did in this case, by showing, when ECHO is On, the variable name rather than it's contents.)
Also, when trimming the last character of a string you don't need 0 in :~0,-1
, using :~,-1
is sufficient. Though there is no harm in doing it either way.
And lastly, the echo on
is unnecessary, as echo on
is the default. Echo On
is more for just displaying small parts of the execution of a long file. Though, once again, there is no harm in it.
@echo on
setLocal EnableDelayedExpansion
::set firstline to firstline of test.txt
set /p firstline=<test.txt
::Remove trailing slash if present
::Your error is below this
IF "!firstline:~-1!"=="\" SET firstline=!firstline:~,-1!
::Output firstline (without \ to new txt file)
echo !firstline!>test2.txt
endlocal