How to sort a Markdown Table with Bash

You can’t sort a markdown table perfectly with sort alone, but you could either manually edit the first to lines or combine with head and tail to get mostly there.

| Fruit  | Type   |
| ------ | ------ |
| Orange | Citrus |
| Apple  | -      |
| Banana | -      |
| Lemon  | Citrus |
| Mango  | -      |

To get the header:

head -n 2 Table.md > Table.sorted.md

Sort the body:

tail -n +3 Table.md | sort -t'|' -k2 --ignore-case >> Table.sorted.md

You’ll get a good result:

cat Table.sorted.md
| Fruit  | Type   |
| ------ | ------ |
| Apple  | -      |
| Banana | -      |
| Lemon  | Citrus |
| Mango  | -      |
| Orange | Citrus |

Using only Unix sort

Set the delimeter to |: -t'|'

The 1st column will actually be the 2nd column: -k2.

sort -t'|' -k2 --ignore-case Table.md
| ------ | ------ |
| Apple  | -      |
| Banana | -      |
| Fruit  | Type   |
| Lemon  | Citrus |
| Mango  | -      |
| Orange | Citrus |

And with a tiny bit of manual editing:

| Fruit  | Type   |
| ------ | ------ |
| Apple  | -      |
| Banana | -      |
| Lemon  | Citrus |
| Mango  | -      |
| Orange | Citrus |

The 2nd column will actually be the 3rd column: -k3.

sort -t'|' -k3 --ignore-case Table.md
| Apple  | -      |
| Banana | -      |
| Mango  | -      |
| ------ | ------ |
| Lemon  | Citrus |
| Orange | Citrus |
| Fruit  | Type   |

Again, manually fix the header and delimiting row:

| Fruit  | Type   |
| ------ | ------ |
| Apple  | -      |
| Banana | -      |
| Mango  | -      |
| Lemon  | Citrus |
| Orange | Citrus |