I came across something puzzling while researching an alternative method of trimming whitespace (spaces and/or tabs) from the head and tail of a string. To trim any whitespace on the left of a string, simply do this:
Code: Select all
for /f "tokens=*" %%a in ("%string%") do set "string=%%a"
It’s as simple as that… or is it? I have to do more testing, but I suspect the usual poison characters and unbalanced quotes may cause problems. But that’s another topic.
What’s puzzling me is this slightly different code taken from this 2008 alt.msdos.batch thread:
Code: Select all
for /f "tokens=*" %%a in ('echo(%string% ') do set "string=%%a"
set "string=%string:0,-1%"
Not only does it trim any whitespace from the left and right of the string, it also condenses any internal multiplespaces or tabs to a single instance.
I don’t understand how a small change in the for /f loop’s in (…) clause can have such a dramatic effect on the output. Can anyone shed some light on this for me?
Thanks!
- SB