Sorting Markdown Tables by Column from the Shell

null

TableFlip doesn't sort tables by column as of yet. So we all have to resort to other solutions – like shell or Terminal commands.

Let's say your (Multi)Markdown table starts with a header (=2 rows) and has leading pipes like this:

| a | b | c | d |
| - | - | - | - |
| 1 | 2 | 3 | 4 |
| 9 | 1 | 2 | 3 |
| 3 | 4 | 5 | 6 |

You can sort the table by the 3rd column (column "c") like so:

tail -n +3 table.md | sort --field-separator=\| --key=4

Explanation:

  • tail reads a file from the end; tail -n +3 reads a file from the end until the 3rd row, leaving out the first 2 rows, aka the header.
  • sort sorts the textual input; --field-separator=\| configures the sort command to not use tab stops but pipes as column separators; and --key=4 sets the 4th field (3rd column if your table starts with a pipe, which is counted by sort, too) as the input.

The output will be:

| 9 | 1 | 2 | 3 |
| 1 | 2 | 3 | 4 |
| 3 | 4 | 5 | 6 |

You can add the header back by combining tail with head, where head outputs the topmost 2 lines:

head -n 2 table.md && tail -n +3 table.md | sort --field-separator=\| --key=4

Et voilà:

| a | b | c | d |
| - | - | - | - |
| 9 | 1 | 2 | 3 |
| 1 | 2 | 3 | 4 |
| 3 | 4 | 5 | 6 |

Ready to be saved as a new file by routing the output to a new file name with > sorted_file.md:

(head -n 2 table.md && tail -n +3 table.md | sort --field-separator=\| --key=4) > sorted_table.md

Browse the blog archive