Reputation: 1
I have a text file with fixed length data. The file contains 3 fields. The first one is 7 characters, the second is 19 characthers and the last one is 6 characters. I wrote a batch file to convert it into a CSV file. Due to organization restrictions i can't install any outer programs like powershell so i need it to be pure DOS commands I wrote the following script but it seems that i missed something. Any ideas?
for /F "tokens=*" %%A in (test.txt) do (
set %MYVAR%=%%A
set mer=%MYVAR:~0,7%
set cr=%MYVAR:~7,19%
set dt=%MYVAR:~26,6%
set "y=%mer%,%cr%,%dt%"
echo %y%>> test.csv
Upvotes: 0
Views: 2792
Reputation: 24466
Depending on what you're doing with this CSV file after it's converted, you might be able to interact with your fixed-width text file as a CSV file natively with no substring extraction or conversion. Just create a Schema.ini
file within the same directory as your fixed-width file with the following contents:
[filename.txt]
ColNameHeader=False
CharacterSet=1252
Format=FixedLength
Col1=mer Text Width 7
Col2=cr Text Width 19
Col3=dt Text Width 6
And voila! The MS Jet, Ace, and other text-mode drivers should now recognize your fixed width file as a CSV file with no massaging.
On a side note, if you'd like a batch utility for interacting with CSV files, you might find this useful.
Upvotes: 0
Reputation: 6630
In batch, when using variables in a code block (that is code inside parenthesis's) you need to enabledelayedexpansion
and use exclamation marks instead of percentage signs.
setlocal enabledelayedexpansion
for /F "tokens=*" %%A in (test.txt) do (
set var=%%A
set mer=!var:~0,7!
set cr=!var:~7,19!
set dt=!var:~26,6!
set "y=!mer!,!cr!,!dt!"
echo !y!>> test.csv
)
Which should do what you want.
Upvotes: 1