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:

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