Q:

echo multiple lines and append each line

I'm trying to format the output of one file into another file at a command line.
FOR /F %i IN (list.txt) DO set num=%i && echo %num:~0,2% %num:~2,2% %num:~4,4% _  _____ >>temp.txt

contents of list.txt
41460729
41640140

desired output:
41 46 0729 _ ____
41 64 0140 _ ____

the first time I run it I get:
%num:~0,2% %num:~2,2% %num:~4,4% _  _____
%num:~0,2% %num:~2,2% %num:~4,4% _  _____ 

the second time I get:
41 64 0140 _ ______ 
41 64 0140 _ ______

I can't figure out why %num% is not working correctly.

A:

That is because normal expansion using percents occurs when the line is parsed, and the entire FOR statement is parsed before the loop executes, so the num variable has not been set yet.
The second time you run, the num variable has already been defined from the last iteration of the prior run. So you get the same values for each iteration.
There is one convenient solution for the command line:
CALL introduces another level of parsing that occurs for each iteration. A caret (^) is included within each variable expansion to prevent any pre-existing value from being expanded during the initial parse phase. The first parse removes the caret, and then the value is properly expanded for each iteration.
FOR /F %i IN (list.txt) DO set num=%i & call echo %^num:~0,2% %^num:~2,2% %^num:~4,4% _  _____ >>temp.txt

Things change if you use a batch file. There are two convenient batch solutions:
1) Use CALL like before, but the syntax changes. In batch you need to double the percents to prevent the value from expanding during the initial parse phase.
FOR /F %%i IN (list.txt) DO set num=%%i & call echo %%num:~0,2%% %%num:~2,2%% %%num:~4,4%% _  _____ >>temp.txt

2) Use delayed expansion that occurs at execution time. This is significantly faster, and generally preferred over the CALL method.
setlocal enableDelayedExpansion
FOR /F %%i IN (list.txt) DO set num=%%i & call echo !num:~0,2! !num:~2,2! !num:~4,4! _  _____ >>temp.txt

Note - Regardless what method you use, you can improve performance by only performing redirection once. The code above performs redirection for each iteration, which slows the process down. Doing only one redirection also allows you to use > so that your file starts empty. I'll use the delayed expansion method below, but any of them will work.
setlocal enableDelayedExpansion
(FOR /F %%i IN (list.txt) DO set num=%%i & call echo !num:~0,2! !num:~2,2! !num:~4,4! _  _____ ) >temp.txt

If you really want to append to any existing data that may exist before your loop, then you can revert to using >>, but adding the parentheses to force only one redirection is still faster.

