Kay
Kay

Reputation: 2067

Convert .txt to .csv in shell

I have a text file:

ifile.txt
1  4    22.0  3.3 2.3
2  2    34.1  5.4 2.3
3  2    33.0 34.0 2.3
4 12     3.0 43.0 4.4

I would like to convert it to a csv file:

ofile.txt
ID,No,A,B,C
1,4,22.0,3.3,2.3
2,2,34.1,5.4,2.3
3,2,33.0,34.0,2.3
4,12,3.0,43.0,4.4

I was trying with this, but not getting the result.

(echo "ID,No,A,B,C" ; cat ifile.txt) | sed 's/<space>/<comma>/g' > ofile.csv

Upvotes: 24

Views: 103373

Answers (7)

Datti
Datti

Reputation: 1

Using:

cat filename | column -t -s ","

We can convert flat file into csv format in unix server

Upvotes: 0

rashedcs
rashedcs

Reputation: 3725

Simply do it using awk command .

 awk '{
     printf("%d, %d, %.1lf, %.1lf,%.1lf\n", $1,$2,$3,$4,$5); 
 }'  input.txt > output.csv

Upvotes: 3

sumitya
sumitya

Reputation: 2691

Only sed and nothing else

sed 's/ \+/,/g' ifile.txt > ofile.csv

cat ofile.csv

1,4,22.0,3.3,2.3
2,2,34.1,5.4,2.3
3,2,33.0,34.0,2.3
4,12,3.0,43.0,4.4

Upvotes: 28

BertramLAU
BertramLAU

Reputation: 430

here is the awk version
awk 'BEGIN{print "ID,No,A,B,C"}{print $1","$2","$3","$4","$5}' ifile.txt

output:

ID,No,A,B,C 
1,4,22.0,3.3,2.3 
2,2,34.1,5.4,2.3 
3,2,33.0,34.0,2.3
4,12,3.0,43.0,4.4

Upvotes: 8

Jonathan Leffler
Jonathan Leffler

Reputation: 753585

One possibility, not necessarily the best, is:

 sed -e '1i\
 ID,No,A,B,C' -e 's/[[:space:]]\{1,\}/,/g' ifile.txt

Insert the heading before line 1; change each sequence of one or more space-like characters to a comma. The line break is necessary in traditional (POSIX standard — in this case, BSD or Mac OS X) sed; GNU sed allows you to use:

/opt/gnu/bin/sed -e '1i\' -e 'ID,No,A,B,C' -e 's/[[:space:]]\{1,\}/,/g'

Output:

ID,No,A,B,C
1,4,22.0,3.3,2.3
2,2,34.1,5.4,2.3
3,2,33.0,34.0,2.3
4,12,3.0,43.0,4.4

Alternatively, and more simply, have sed deal with the file and use echo to add the header, as you did in outline:

{
echo "ID,No,A,B,C"
sed -e 's/[[:space:]]\{1,\}/,/g' ifile.txt
} > ofile.txt

On review, this is probably what I'd use.

Upvotes: 2

Amey Jadiye
Amey Jadiye

Reputation: 3154

Try this ..

tr -s " " < ifile.txt | sed 's/ /,/g' > ofile.txt

OUTPUT

1,4,22.0,3.3,2.3
2,2,34.1,5.4,2.3
3,2,33.0,34.0,2.3
4,12,3.0,43.0,4.4

Upvotes: 2

Mureinik
Mureinik

Reputation: 311163

awk may be a bit of an overkill here. IMHO, using tr for straight-forward substitutions like this is much simpler:

$ cat ifile.txt | tr -s '[:blank:]' ',' > ofile.txt

Upvotes: 26

Related Questions