Alan Jebakumar
Alan Jebakumar

Reputation: 317

Creating a CSV file from a text file

i have the below text file in this format

2015-04-21
00:21:00
5637
5694
12
2015-04-21
00:23:00
5637
5694
12

I want to create a csv file like the below one-

2015-04-21,00:21:00,5637,5694,12
2015-04-21,00:23:00,5637,5694,12

i used the tr and the sed like this-

cat file | tr '\n' ',' | sed 's/,$//'

It results in the below way-

2015-04-21,00:21:00,5637,5694,12,2015-04-21,00:23:00,5637,5694,12

but it doesn't have an new line after the column 5.

Do suggest a solution.

Upvotes: 0

Views: 48

Answers (2)

zedfoxus
zedfoxus

Reputation: 37059

Use awk like so:

awk 'ORS=NR%5 ? "," : "\n"'

$ cat test.txt
2015-04-21
00:21:00
5637
5694
12
2015-04-21
00:23:00
5637
5694
12

$ awk 'ORS=NR%5 ? "," : "\n"' test.txt
2015-04-21,00:21:00,5637,5694,12
2015-04-21,00:23:00,5637,5694,12

Explanation:

  • ORS stands for output record separator
  • NR is number of records
  • NR % 5 - % is modulo operator. If it is zero (every 5th record), use line feed. Otherwise, use comma

Upvotes: 1

Mohit
Mohit

Reputation: 119

a simple solution in python

fin = open('file','r')
fout = open('outputfile','w')
a=[]
i=0
for line in fin:
    a.append(line.rstrip())
    i+=1
    if i==5:
        fout.write(','.join(a)+'\n')
        a=[]
        i=0
fin.close()
fout.close()

Upvotes: 0

Related Questions