I am trying to process a text file that looks like this:
"N" "accounts" "General" no "0001"
"N" "accounts" "Customer" no "0002"
and so on
The batch file looks like this:
setlocal EnableDelayedExpansion
set TGT=schctrl
set TMP=schctrl.tmp
copy %TGT% %TMP%
set NWOV=accounts inventory generalledger headoffice
for %%a in (%NWOV%) do (
for /f "tokens=2,5 delims= " %%D in ('findstr /i %%a %TMP%') do (
set M=%%E
set M=%M:"=%
echo %%D %%E %M%
)
)
The command, set M=%M:"=%
, doesn't strip off all the quotation marks!
When I run it, I get output like this:
set M="1148"
set M=!M:"=!
echo "accounts" "1148"
I am expecting the last line to look like this:
"accounts" "1148" 1148
The last field is missing.
I am guessing the culprit is the for
loop, and expansion of variables, but I have been grinding away on this and have not yet found the solution.
When you open cmd
and run for /?
. Scroll down to the section on Substitution
and read the first line:
Therefore %%E
will contain quotes and %%~E
won't contain quotes. So, just changing that meta variable in the code:
@echo off
set "TGT=schctrl"
set "TMP_FILE=schctrl.tmp"
copy "%TGT%" "%TMP_FILE%"
set "NWOV=accounts inventory generalledger headoffice"
for %%a in (%NWOV%) do (
for /f "tokens=2,5 delims= " %%D in ('findstr /i %%a %TMP_FILE%') do (
echo %%D %%E %%~E
)
)
As a side note, the reason why your search/replace did not work is because you enable
d delayedexpansion
but you never used it. For that you needed to replace %
with !
in the variables you are expanding within the loop, so !M!
instead of %M%
That being said, please do not use single characters as variable names it will create confusion.
Also, as stated by Magoo in the comments, do not re-use system variables, like %TMP%
.