Tamaghna Guha Thakurta Tamaghna Guha Thakurta -4 years ago 123
Bash Question

Bash Script to generate csv file from text

I have a text file with records:

Data1

Data2

...

Data50


I have to create a .csv file from the above text file in the following format:

Type | Count | Name

Def | u1 | Data1

Def | u2 | Data2

.... | ..... | ....

Def | u50 | Data50


i need a bash script to generate the .csv file from the text file. I am new to shell scripting! I have gone through basics of awk and sed as well.
I have a vague idea like:

#!/bin/bash
type="Def"
x=1
count="u"
for F in ../test.txt
do
{
read \n
echo "$type, $count$x, $..." >> ../test.csv
x=x+1
} < $F

done


I do understand that the field separator is '\n'. I am kind of lost after that.

Thanks!

Answer Source

save this in a file, e.g. makecsv.rc:

#!/bin/sh
echo Type,Count,Name
x=0
for f in `cat`
do
   x=`expr $x + 1`
   echo Def,u$x,$f
done

then run as:

cat  ../test.txt | ./makecsv.rc > ../test.csv

if needed, you do chmod +x makecsv.rc

The advantage is that the input/output file names are not hardcoded

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download