1

How do I extract everything between incno and the space ie12345678 in the example batch below and put it into a incno variable?

@echo off  
Set mystring=test incno12345678 wo5555 locFred Street   
Echo "my string=%mystring%"   
Echo incno   
Echo wo    
Echo loc  

The incno can be 8 to 11 digits long but will always be between incno and a space in the string

I am now having trouble assigning the %%d variable to the mystring variable now it is in a for loop. Can anyone help me with this? See Below.

@echo off
SETLOCAL enableDelayedExpansion
color 0B
For /d %%d in ("C:\Users\%Username%\LocalData\*") do (
Echo "Folder = %%d"
Set mystring=%%d
echo "MyString = %mystring%"
pause
REM delete until (including) "incno":
set mystring=%mystring:*incno=%
echo %mystring%
REM delete starting with (including) " ":
set mystring=%mystring: =&rem %
echo "Incident Number = %mystring%"
pause
)

2 Answers 2

4

you can do it with substring replacement in two steps:

Set mystring=test incno12345678 wo5555 locFred Street
echo %mystring%
REM delete until (including) "incno":
set mystring=%mystring:*incno=%
echo %mystring%
REM delete starting with (including) " ":
set mystring=%mystring: =&rem %
echo %mystring%
Sign up to request clarification or add additional context in comments.

7 Comments

How does set mystring=%mystring: =&rem % work? I can't find that documented anywhere? What does the &rem do?
@DavidPostill - Do the replacement on paper and you will see. It simply inserts a concatenated REM command, so the rest of the string is ignored.
The only problem with this technique is it is not immune to issues with a mixture of poison characters and quotes, nor can it be modified to be so.
@sambul35 ss64 is always my first point of reference, and I know (in general) how to use string replacement (which is evident if you look at my answers on Super User). However, it does not describe that particular trick (which is new to me) and is obvious when it is pointed out by the master :)
@DavidPostill: you may review more examples of this trick at this thread.
|
2
set "mystring=test incno12345678 wo5555 locFred Street"
for /f %%V in ("%mystring:* incno=%") do set "incno=%%V"

Delayed expansion can be used if there is a chance that mystring might contain poison characters plus quotes:

setlocal enableDelayedExpansion
set mystring=test incno12345678 wo5555 loc"4th & Main"
for /f %%V in ("!mystring:* incno=!") do set "incno=%%V"

If the resultant value might contain ! (not an issue in this case) then delayed expansion must be toggled

setlocal disableDelayedExpansion
set mystring=test varABC!XYZ "&)^|<>"
setlocal enableDelayedExpansion
for /f %%V in ("!mystring:* var=!") do (
  endlocal
  set "var=%%V"
)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.