Stig Brautaset
Stig Brautaset

Reputation: 2632

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

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!

Upvotes: 6

Views: 1216

Answers (1)

Mike Fletcher
Mike Fletcher

Reputation: 76

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

Upvotes: 6

Related Questions