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
1

6 Answers

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
1

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
5

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

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
0

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.

Simply do it using awk command .

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest