SRel
SRel

Reputation: 423

Batch: Replacing just the first character in a string if it is a certain character

I have several datalines like so:

v1.4.00.29                                                           
- SP.CNG v1.0.2.2                                                           
Update Kit - Secure USB Token v1.1.1.1                                                           
- HI_3997 v1.0.3997.1                                                           
- HI_4009 v1.0.4009.1                                                           
- HI_3585 v1.0.3585                                                           
Update Kit - RM4 v1.0.1202.4                                                           
Update Kit - DN Series v1.0.4.1   

Is there some easy way to check if the first character is a - and then delete this PLUS the space next to them so that the line is aligned to the other lines.

My first try was just to delete the -and spacesresulting in a not looking result as ALL - are replaced:

set tmp=!tmp:-=!
set tmp=!tmp: =!

Upvotes: 3

Views: 1753

Answers (2)

aschipfl
aschipfl

Reputation: 34929

You might want to try the following code that uses sub-string substitution (the string to process is stored in variale tmp):

if "- !tmp:*- !"=="!tmp!" set "tmp=!tmp:*- =!"

This removes everything up to and including the first occurrence of - + SPACE from the string and precedes the result with - + SPACE; if this is now equal to the original string then the first - + SPACE must be at the beginning, so remove it; otherwise do not alter the string.

Upvotes: 0

TripeHound
TripeHound

Reputation: 2960

You can do this using the "substring" method of referring to environment variables. In brief:

%TMP:~n,m%

will extract m characters from TMP, starting with the nth, where counting starts from zero. (You can also omit ,m to get "the rest of the string" and use negative numbers to mean "from the end of the string" – see the output of SET /? for more details).

In your case, something like the following should work:

if "%TMP:~0,2%" == "- "     set "TMP=%TMP:~2%"

This checks whether the first two characters are a minus and a space (you could relax this to just checking the first character if needed). If there's a match, it replaces TMP with all characters starting with the third (0=1st, 1=2nd etc.).

Upvotes: 3

Related Questions