Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert .txt to .csv in shell

Tags:

linux

shell

csv

awk

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
like image 353
Kay Avatar asked May 24 '16 06:05

Kay


People also ask

How do I convert a TXT file to CSV?

Go to File > Save As. Click Browse. In the Save As dialog box, under Save as type box, choose the text file format for the worksheet; for example, click Text (Tab delimited) or CSV (Comma delimited).

Can you save TXT file as CSV?

For PC, head to the "File" menu, and choose "Save as". You'll type in the name of your file, and add the extension ". csv". This will automatically change it to CSV format!

How do I convert a CSV file to a text file in Linux?

So just in case you are using a text only browser, or need to cut and paste, Lukas's answer is to go into your command line, navigate to the right directory and type the command: “cut -d, -f3 report_source. csv | sed 's/”//g > report_links. txt” (without the quotes).


2 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
like image 58
sumitya Avatar answered Sep 19 '22 14:09

sumitya


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
like image 29
Mureinik Avatar answered Sep 20 '22 14:09

Mureinik