哈喽大家好,我是咸鱼。
今天分享一个很实用的 bash 脚本,可以通过手动提供单元格内容和列数或者将带有分隔符的文件(如 CSV、TSV 文件)转换为 Markdown 表格。
源代码在文末哦!原文链接:https://josh.fail/2022/pure-bash-markdown-table-generator/
具体功能:
- 手动生成表格:允许用户输入表格内容和列数,生成标准的 Markdown 格式表格。
- 文件转换:可以将 CSV 或 TSV 文件转换为 Markdown 表格。
- 选项支持:支持指定列数、设置分隔符、解析 CSV/TSV 文件等选项。
主要选项:
-COLUMNS
:设置生成表格的列数。-sSEPARATOR
:自定义输入文件的列分隔符。--csv
和--tsv
:分别用于解析 CSV 和 TSV 文件。
几个月前,我想要一个便携式的 Markdown 表格生成器,于是写了这个 markdown-table
脚本。
一开始我只是想传入一堆参数和列数,并让它生成相应的 Markdown 表格。就像下面的例子:
markdown-table -4 \
"Heading 1" "Heading 2" "Heading 3" "Heading 4" \
"Hi" "There" "From" "Markdown\!" \
"Everything" "Is" "So" "Nicely Aligned\!"
当我实现了这一功能后,我意识到还可以添加支持解析带有自定义分隔符的文件,比如 CSV 或 TSV。
markdown-table --tsv < test.tsv
上面两种方法都会生成一个 Markdown 表格:
| Heading 1 | Heading 2 | Heading 3 | Heading 4 |
| ---------- | --------- | --------- | -------------- |
| Hi | There | From | Markdown |
| Everything | Is | So | Nicely Aligned |
#!/usr/bin/env bash
# Usage: markdown-table -COLUMNS [CELLS]
# markdown-table -sSEPARATOR < file
#
# NAME
# markdown-table -- generate markdown tables
#
# SYNOPSIS
# markdown-table -COLUMNS [CELLS]
# markdown-table -sSEPARATOR < file
#
# DESCRIPTION
# markdown-table helps generate markdown tables. Manually supply arguments
# and a column count to generate a table, or pass in a delimited file to
# convert to a table.
#
# OPTIONS
# -COLUMNS
# Number of columns to include in output.
#
# -sSEPARATOR
# String used to separate columns in input files.
#
# --csv
# Shortcut for `-s,` to parse CSV files. Note that this is a "dumb" CSV
# parser -- it won't work if your cells contain commas!
#
# --tsv
# Shortcut for `-s$'\t'` to parse TSV files.
#
# -h, --help
# Prints help text and exits.
#
# EXAMPLES
# Build a 4 column markdown table from arguments:
# markdown-table -4 \
# "Heading 1" "Heading 2" "Heading 3" "Heading 4" \
# "Hi" &