Articles

Create, files based on column

June 21, 2010 at 09:05:11
Specs: Windows XP

I can't seem to figure out this simple problem:
I have 1 file that has 4 columns:
column 1= filename
column 2-4=data

I need to take column1, create a file with that name, and then create 3 rows with columns 2-4.

for example the input.txt looks like:
----------------------------
file1,A,B,C
file2,D,E,F
file3,G,H,I
----------------------------
and I need a new file: "file1.txt" with the following text
----------------------------
A
B
C
----------------------------
I can create the new files with the batch below, but can't get the data to the right file:
----------------------------
for /f "tokens=1 delims=," %%a in (input.txt) do (
set str=%%a
@echo off>%%a.txt)
-------------------------------------
Thanks for the help.


See More: Create, files based on column

Report •


#1
June 21, 2010 at 09:49:51

You are real close!
Set tokens=1-4, so you also create variable %%b, %%c, and
%%d which will hold the values of columns 2-4. Now echo
%%b, %%c, and %%d into file %%a using >> which will
append to file %%a.

Alternate method not using @echo off>%%a.txt:
echo %%b > "%%a.txt"
echo %%c >> "%%a.txt"
echo %%d >> "%%a.txt"

Also, set str=%%a is not really doing anything because
you're not referencing %str% elsewhere in the batch...

HTH!

Insomniac at large


Report •

#2
June 21, 2010 at 11:28:03

note: i've learned the hard way that:
echo %%b > "%%a.txt"
puts a space at the end of the line, which prob'ly not an issue in this post but ya never know.
alternatives:
echo %%b> "%%a.txt"
or:
> "%%a.txt" echo %%b

Report •

#3
June 21, 2010 at 11:30:14

I typically use that last method myself. It makes the code look
nicer :-)

Insomniac at large


Report •

Related Solutions

#4
June 22, 2010 at 09:50:12

Perfect. Thanks a ton. This will save us hours of tedious work.
I'm a civil engineer who has never done much computer programing, but have found that I waste a lot of time doing stupid things that very simple little batch files like this can do. Thanks again.

For those (if any) looking at this post here is the final batch that I put together (I like to see the finished product, it helps me):

::This creates text files with the name from column 1, and rows from columns 2-4
:: Input "columns.txt":
:: file1,A,B,C
:: file2,D,E,F
:: file3,G,H,I
:: Output = 3 files named file1.txt, file2.txt and file3.txt
:: --- file1.txt ---

:: [line1] A
:: [line2] B
:: [line3] C
::
@echo off
for /f "tokens=1-4 delims=," %%a in (columns.txt) do (
@echo %%b>%%a.txt
@echo %%c>>%%a.txt
@echo %%d>>%%a.txt)
:: End create text file


Report •


Ask Question