Ubuntu – Create a CSV file from a TXT file

command linecsv

How do I create a CSV file from a TXT file as per the following example? Thanks.

TXT file:
This is line number one
This is line number two with extra words
This is line number three with even more words
Resulting CSV file:
Col#1 Col#2 Col#3 Col#4  Col#5 Col#6 Col#7 Col#8 Col#9
This  is    line  number one
This  is    line  number two   with  extra words
This  is    line  number three with  even  more  words

Edit: Well, my question is different from and hence not a duplicate of:

https://askubuntu.com/questions/1214146/trying-to-create-a-csv-file-from-a-text-file-in-ubuntu

because the other question is asking to "organize" each line in to "columns", while my question is about organizing each word (separated by whitespaces) into a new column. Thanks.

Best Answer

It depends what you mean by a "word", and what you mean by a "CSV file".

If you just want to convert horizontal whitespace to commas, you could use something like

tr -s '[:blank:]' , < file.txt > file.csv

or

sed 's/[[:blank:]]\{1,\}/,/g' file.txt > file.csv

or

awk '{$1=$1} 1' OFS=, file.txt > file.csv

If you want a header row (especially if it needs to count the maximum number of columns) and / or things like `NULL's for unpopulated fields, it will be more complicated.