哈喽大家好,我是咸鱼。
今天分享一个很实用的 bash 脚本,可以通过手动提供单元格内容和列数或者将带有分隔符的文件(如 CSV、TSV 文件)转换为 Markdown 表格。
源代码在文末哦!原文链接:https://josh.fail/2022/pure-bash-markdown-table-generator/
具体功能:
主要选项:
-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
上面两种方法都会生成一个 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 &2
}
# Print the help text for this program
#
# $1 - flag used to ask for help ("-h" or "--help")
print_help() {
sed -ne '/^#/!q;s/^#$/# /;/^# /s/^# //p' max )) && max="$arg"
done
printf "%s" "$max"
}
# Formats a table in markdown format
#
# $1 - field separator string
format_table() {
local fs="$1" buffer col current_col=0 current_row=0 min=3
local -a lengths=()
buffer="$(cat)"
# First pass to get column lengths
while read -r line; do
current_col=0
while read -r col; do
lengths["$current_col"]="$(max "${#col}" "${lengths[$current_col]}")"
current_col=$((current_col + 1))
done
参与评论
手机查看
返回顶部