[K12OSN] OT: Bash help

Robert Arkiletian robark at gmail.com
Tue Nov 20 04:13:10 UTC 2007


On Nov 19, 2007 11:16 AM, Peter Hartmann <peter at hartmanncomputer.com> wrote:
> Hey Robert,
> I always forget to paint the bigger picture....I'm making a csv file
> from many textfiles.    This last part works well....so I'm hoping to
> keep it.  Eventually there will be LOTS of fields, not just 2.
>
> LIMIT=400
> for ((a=0; a <= LIMIT ; a++))
> do
>    echo  ${ffirst[$a]}:${flast[$a]} # >> contacts.csv
> done
> echo; echo

Okay Peter how is this?
if I understand correctly you have multiple files

file1    file2   file3

bob    14      male
kate   13      female
john   15      male
sue    16      female

where each file contains info fields that are in order (so bob is 14
and he is male)
which you want to change into one file

contacts

bob:14:male
kate:13:female
john:15:male
sue:16:female

rename your files (or cp them)
instead of ffirst , fsecond, fthird, ...
make them
f1,f2,f3,....

then try this (no promise it will work as I'm still not 100% sure this
is what your want)

#!/usr/bin/python
outfile = file('contacts.cvs','w')
filelist=[]
for i in range(1,41): #I'm assuming you have 40 files to read from
   namelist=[]
   f = file('f'+str(i),'r')
   for x in f.readlines():
      namelist.append(x[:-1]) # [:-1] to remove enter
   filelist.append(namelist)
   f.close()
for x in range(0, len(filelist[1])): #assuming all files same length
   contact=[]
   for y in range(0, len(filelist)):
      contact.append(filelist[y][x])
   outfile.write(":".join(contact)+"\n")
outfile.close()

Remember white space matter in Python. I have used 3 spaces to indent
(usually you should use 4)
Let me know if it works. This is the type of stuff I would give to my
senior students. Good exercise. I may even assign it. Here's hoping
they don't read this list. :)

-- 
Robert Arkiletian
Eric Hamber Secondary, Vancouver, Canada
Fl_TeacherTool http://www3.telus.net/public/robark/Fl_TeacherTool/
C++ GUI tutorial http://www3.telus.net/public/robark/




More information about the K12OSN mailing list