Create a CSV file from a TXT file

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:

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.

9

1 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.

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like