How can I produce a table with column headers from org-babel shell output?
Asked Answered
E

1

6

I'm trying to add headers to this:

#+BEGIN_SRC sh :dir ~ :results table
  for n in 1 2 3 4; do
      echo $n $(($n * $n))
  done
#+END_SRC

Which results in:

#+RESULTS:
| 1 |  1 |
| 2 |  4 |
| 3 |  9 |
| 4 | 16 |

The output I want is:

#+RESULTS:
| N | N*N |
|---+-----|
| 1 |   1 |
| 2 |   4 |
| 3 |   9 |
| 4 |  16 |

The difficulty I'm having is injecting the second line. This does not work:

#+BEGIN_SRC sh :dir ~ :results table
  echo "N N**2"
  echo "|-"
  for n in 1 2 3 4; do
      echo $n $(($n * $n))
  done
#+END_SRC

This results in:

#+RESULTS:
| N | N**2 |
|   |    - |
| 1 |    1 |
| 2 |    4 |
| 3 |    9 |
| 4 |   16 |

Neither can I just use a blank line, as suggested here:

#+BEGIN_SRC sh :dir ~ :results table
  echo "N N**2"
  echo 
  for n in 1 2 3 4; do
      echo $n $(($n * $n))
  done
#+END_SRC

As this results in:

#+RESULTS:
| N | N**2 |
|   |      |
| 1 |    1 |
| 2 |    4 |
| 3 |    9 |
| 4 |   16 |

Any hints greatly appreciated!

Ency answered 22/1, 2016 at 15:55 Comment(0)
R
6

I think :results org is what you're looking for, and then make your code output what you'd type yourself as a table with separators (quoted to protect from the shell)

#+BEGIN_SRC sh :dir ~ :results org
  echo "|N|N**2"
  echo "|-"
  for n in 1 2 3 4; do
      echo "|" $n "|" $(($n * $n))
  done
#+END_SRC

That produces this (emacs 25.1.50.1, org 8.3.3):

#+RESULTS:
#+BEGIN_SRC org
| N | N**2 |
|---+------|
| 1 |    1 |
| 2 |    4 |
| 3 |    9 |
| 4 |   16 |
#+END_SRC
Raymund answered 27/1, 2016 at 21:1 Comment(3)
This is close, but when exporting this it shows verbatim. However, if you use :results org drawer rather than just :results org then it exports as a nice table :-)Ency
BTW, did you just join to answer this? Thanks a lot :-)Ency
Great question and answer. Still, it would be useful to be able to just add headers to rows and columns as a post-processing step and not to depend on your particular language to take care of that.Keller

© 2022 - 2024 — McMap. All rights reserved.