0

I have two different textfiles.txt (textfile1.txt and textfile2.txt) with different data sets in them. Is it possible to compile two seperate .txt files as a single CSV file?

UPDATE

textfile1.txt has values written in this format:

 20
 31
 18
 -11
 12
 19

textfile2.txt has values written in this format:

100.000 200.000 300.000
101.000 201.000 301.000
102.000 202.000 302.000
103.000 203.000 303.000
104.000 204.000 304.000
105.000 205.000 305.000

I wish for my output to be in following format:

 20,100.000,200.000,300.000
 31,101.000,201.000,-301.000
 18,-102.000,202.000,302.000
-11,103.000,203.000,303.000
 12,104.000,204.000,304.000
 19,105.000,-205.000,305.000
  • 1
    Are the two text files CSVs themselves? – polemon Jan 8 '16 at 19:00
  • 1
    Yes it is, but in order for us to help you, you need to show us an example of your files and the output you would like to see. How exactly should they be combined? Should file2 be added to file1? Should line1 of file2 be added to line1 of file1? Edit your question to clarify it and it can be reopened. – terdon Jan 10 '16 at 23:16
  • 1
    Just a suggestion - to clarify the transformation - could you show textfile1.txt with different numbers in it? Or are they always 20? – Jeff Schaller Jan 11 '16 at 19:43
  • @JeffSchaller Just updated it to make it clearer. Hope this helps~ – JolyDroneSP Jan 12 '16 at 10:21
3

If all you want to do is combine the two files then cat textfile1.txt textfile2.txt > combined.txt will do that.

  • I wish to combine the two files and convert the result to a CSV file, where the information of textfile1.txt and textfile2.txt are in seperate columns. – JolyDroneSP Jan 9 '16 at 5:01
  • @JolyDroneSP that detail should be added to the question, – Jasen Jan 10 '16 at 8:49
3

paste will join files side by side

paste -d, file1 file2

if the files may contain commas or quotes but are not CSV data themselves, they will need to all be quoted first.

paste -d, \
 $<( sed 's/"/""/g;s/^/"/;s/$/"' < file1 ) \
 $<( sed 's/"/""/g;s/^/"/;s/$/"' < file1 )

or only the lines containing the special characters

paste -d, \
 $<( sed '/[",]/ { s/"/""/g;s/^/"/;s/$/"; }' < file1 ) \
 $<( sed '/[",]/ { s/"/""/g;s/^/"/;s/$/"; }' < file2 )
  • since the 2nd textfile is not comma-separated, you would need some postprocessing even in the simplest forum: e.g. paste -d, file1 file2 | sed -e 's| *|, |g' – umläute Jan 11 '16 at 22:19
  • @umläute, perhaps sed -e 's/ */,/g' file2 | paste -d, file1 - is better (fix up input). Careful, it is two spaces before * – vonbrand Jan 11 '16 at 23:47
  • @vonbrand good point – umläute Jan 12 '16 at 14:22

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.