Help needed with nested loop in batch file

January 11, 2010 at 06:36:56
Specs: Windows Vista
Apart from simple scripts launching programs, never used a batch file for the following so please bear with me!

Have a directory full of csv files.
I want to use the file name for field1 and then copy the contents of fields 6>11 to fields 3>8. Repeat for all so that the information from X files is held in 1 file that I can import to a db.

Currently the following works BUT I am failing miserably with using a variable for the filename,


cd "K:\test_csv"

@echo off > t1.txt

FOR /F %%a IN ('dir /b *.csv') DO call :s_sub %%a

FOR /F "tokens=2,4 delims=, " %%b IN ("test,Print1,blank,Print2") DO echo %%~na, %%b, %%c >> t1.txt

This works, but when I change ...IN ("test,Print1,blank,Print2") DO... to ...IN (!%%a!) DO... it fails spectacularly!

Any help gratefully received.

(PS before anyone asks, field2 will be "RepDate" which will be found using FIND, though that is a bridge I will cross if this is doable!)

See More: Help needed with nested loop in batch file

Report •

January 11, 2010 at 12:04:47
not for sure exactly what you're looking for, but maybe like this?
@echo off & setlocal enabledelayedexpansion
for %%a in (*.csv) do for /f "tokens=2,4 delims=," %%b in (%%~sa) do (
>>t1.txt echo %%a,%%b,%%c)

Report •

January 12, 2010 at 02:07:34
Doesn't work.

Have stripped it down to look at 1 named file:

for /f "tokens=2,4 delims=," %%b in ('test.txt') do (echo %%b, %%c >> t1.txt)

The script OPENS the test.txt file and does nothing!

Please help or am I trying to get it to do something that is impossible?

Report •

January 12, 2010 at 02:30:33
Not sure why nbrane's script doesn't work; looks ok to me. However, your test:

for /f "tokens=2,4 delims=," %%b in ('test.txt') do (echo %%b, %%c >> t1.txt)

doesn't surprise me that it opens test.txt (in Notepad). Using single quotes makes it execute the enclosed command. Leave out the quotes.

Also, in your initial script, because you sent %%a as a command-line parameter to the sub, use %1 in the sub itself, not %%a.

Report •

Related Solutions

January 12, 2010 at 02:45:52
Thanks. Got it to work. It needed "Type" due to the file not being in ANSI (Is there a way to test this for future reference?)

ie: ...%%b in (%%~sa) do ... is now ,,,%%b in ('type %%~sa') do ...

Thank you

Report •

January 12, 2010 at 22:53:29
there are probably simpler ways test for unicode, but:
@goto :AA

@echo off & setlocal
for /f "skip=3 tokens=2-4" %%a in ('debug \path1\file1^<%0.bat 2^>nul') do (
if "%%a"=="FF" if "%%b"=="FE" echo unicode file

better method:
@echo off & setlocal enabledelayedexpansion
:: determine if a file is unicode or not (without using debug)
set /p xx=<%1
set xx=%xx:~0,2%
echo %xx%>xxx
::fffe contains: FF FE 0D 0A
fc xxx fffe
set uni=%errorlevel%
::errorlevel zero (files same) means unicode, else its ansi
echo %errorlevel%
if %uni% equ 1 (echo ANSI) ELSE (ECHO UNICODE)

Report •

Ask Question