1
$\begingroup$

My data is

data = {{1, 1, 1, 1, 0.469258}, {1, 1, 1, 2, 0.}, {1, 1, 1, 3, -0.000123615}}

On linux-like systems there is a printf routine to make formatted print. How can I use this function from mathematica in order to obtain the formatted text file with 5 columns and 3 rows with a given format.

For instance with printf "%3i %3i %3i %3i %10.6f\n" I am expecting

  1   1   1   1   0.469258
  1   1   1   2   0.000000
  1   1   1   3  -0.000124

Currently I doing

file = "a.dat";
If[FileExistsQ[file], DeleteFile[file]]
cmd = "printf \"%3i %3i %3i %3i %10.6f\\n\"";
Do[
 args = StringRiffle[ToString[#] & /@ s];
 Run[StringRiffle[{cmd, args, ">>", file}]];
 , {s, data}]

But is it an idiomatic method? Will it fail in some cases, like for other variable types or too long strings? Is there a better way?

$\endgroup$
11
  • $\begingroup$ Would Exporting the data as a "Table" (perhaps using appropriate "FieldSeparators" as an option) work for you? $\endgroup$
    – MarcoB
    Feb 27, 2021 at 13:42
  • $\begingroup$ Try: Export["filename", data, "Table"] $\endgroup$ Feb 27, 2021 at 13:50
  • 2
    $\begingroup$ @MarcoB With Exporting plus "FieldSeparators" you almost there, but formatting is difficult. I doubt that MA can exactly conform all the rules that printfis using, or am I wrong? I am not after the speed, but more after the control, accuracy and predictability of output. $\endgroup$
    – yarchik
    Feb 27, 2021 at 14:19
  • 1
    $\begingroup$ Does this answer your question? sprintf() or close equivalent, or re-implementation? $\endgroup$
    – WReach
    Feb 28, 2021 at 17:46
  • 1
    $\begingroup$ I cannot write a full answer at this time, but a couple of suggestions: 1) use ToString@*CForm on each argument so that exponentials are written in C syntax instead of Mathematica syntax, 2) if strings are going to be permitted then any characters with special meaning to the shell must be escaped. $\endgroup$
    – WReach
    Feb 28, 2021 at 21:00

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.