一个能够生成 Markdown 表格的 Bash 脚本
哈喽大家好,我是咸鱼。
今天分享一个很实用的 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" "There" "From" "Markdown!" \
# "Everything" "Is" "So" "Nicely Aligned!"
#
# Convert a CSV file into a markdown table:
# markdown-table -s, < some.csv
# markdown-table --csv < some.csv
#
# Convert a TSV file into a markdown table:
# markdown-table -s$'\t' < test.tsv
# markdown-table --tsv < test.tsv
# Call this script with DEBUG=1 to add some debugging output
if [[ "$DEBUG" ]]; then
export PS4='+ [${BASH_SOURCE##*/}:${LINENO}] '
set -x
fi
set -e
# Echoes given args to STDERR
#
# $@ - args to pass to echo
warn() {
echo "$@" >&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' < "$0" |
awk -v f="$1" '
f == "-h" && ($1 == "Usage:" || u) {
u=1
if ($0 == "") {
exit
} else {
print
}
}
f != "-h"
'
}
# Returns the highest number in the given arguments
#
# $@ - one or more numeric arguments
max() {
local max=0 arg
for arg; do
(( ${arg:-0} > 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 <<< "${line//$fs/$'\n'}"
done <<< "$buffer"
# Second pass writes each row
while read -r line; do
current_col=0
current_row=$((current_row + 1))
while read -r col; do
printf "| %-$(max "${lengths[$current_col]}" "$min")s " "$col"
current_col=$((current_col + 1))
done <<< "${line//$fs/$'\n'}"
printf "|\n"
# If this is the first row, print the header dashes
if [[ "$current_row" -eq 1 ]]; then
for (( current_col=0; current_col < ${#lengths[@]}; current_col++ )); do
printf "| "
printf "%$(max "${lengths[$current_col]}" "$min")s" | tr " " -
printf " "
done
printf "|\n"
fi
done <<< "$buffer"
}
# Main program
main() {
local arg cols i fs="##$$FS##"
while [[ $# -gt 0 ]]; do
case "$1" in
-h | --help) print_help "$1"; return 0 ;;
-[0-9]*) cols="${1:1}"; shift ;;
-s*) fs="${1:2}"; shift ;;
--csv) fs=","; shift ;;
--tsv) fs=$'\t'; shift ;;
--) shift; break ;;
-*) warn "Invalid option '$1'"; return 1 ;;
*) break ;;
esac
done
if [[ -z "$fs" ]]; then
warn "Field separator can't be blank!"
return 1
elif [[ $# -gt 0 ]] && ! [[ "$cols" =~ ^[0-9]+$ ]]; then
warn "Missing or Invalid column count!"
return 1
fi
{ if [[ $# -gt 0 ]]; then
while [[ $# -gt 0 ]]; do
for (( i=0; i < cols; i++ )); do
if (( i + 1 == cols )); then
printf "%s" "$1"
else
printf "%s%s" "$1" "$fs"
fi
shift
done
printf "\n"
done
else
cat
fi
} | format_table "$fs"
}
main "$@"
一个能够生成 Markdown 表格的 Bash 脚本的更多相关文章
- 一个极简的守护进程Bash脚本
由于最近写的Node.js程序因为一些Bug,会出现一些自动退出的问题,所以需要在它退出的时候及时发现,并重新启动 于是查阅了些资料,写了一个Bash的程序,功能十分简单,就是每隔3s判断一次处在60 ...
- 一个自动生成awr报告的shell脚本
最近在学习shell编程,搞一点点小工具自动完成awr报告的收集工作,方便系统出现问题时问题排查.脚本内容如下,系统收集每天开始时间6点结束时间20点的awr报告并存储在/u01/shell_t/aw ...
- Linux 桌面玩家指南:06. 优雅地使用命令行及 Bash 脚本编程语言中的美学与哲学
特别说明:要在我的随笔后写评论的小伙伴们请注意了,我的博客开启了 MathJax 数学公式支持,MathJax 使用$标记数学公式的开始和结束.如果某条评论中出现了两个$,MathJax 会将两个$之 ...
- Bash 脚本编程语言中的美学与哲学
我承认,我再一次地当了标题党.但是不可否认,这一定是一篇精华随笔.在这一篇中,我将探讨 Bash 脚本语言中的美学与哲学. 这不是一篇 Bash 脚本编程的教程,但是却能让人更加深入地了解 Bash ...
- Linux应用环境实战10:Bash脚本编程语言中的美学与哲学(转)
阅读目录 一.一切皆是字符串 二.引用和元字符 三.字符串从哪里来.到哪里去 四.再加上一点点的定义,就可以推导出整个Bash脚本语言的语法了 五.输入输出重定向 六.Bash脚本语言的美学:大道至简 ...
- 采用Bash脚本性能监控过程
为一个Linux过程监控,采用Bash脚本. 采用ps命令的过程监控,使用周期加上连续监测的睡眠时间. 使用方法: psmonitor.sh -p [pid] -d [interval] -n [st ...
- 用 Excel 生成和管理 Markdown 表格--转载
Markdown 作为一种轻量级的标记语言,用来进行简单的文本排版,确实方便快捷.但 Markdown 标记语言的属性,也使得其在表格处理上略显繁琐且不直观.而 Excel 几乎就是表格的代名词,借助 ...
- 一个很不错的bash脚本编写教程
转自 http://blog.chinaunix.net/uid-20328094-id-95121.html 一个很不错的bash脚本编写教程,至少没接触过BASH的也能看懂! 建立一个脚本 Lin ...
- 在ubuntu linux 中编写一个自己的bash脚本
在ubuntu linux 中编写一个自己的简单的bash脚本. 实现功能:终端中输入简单的命令(以pm为例(play music)),来实现音乐的播放.注:本人ununut中安装了audacious ...
- 在Linux环境下实现一个非常好的bash脚本框架
为了方便我日常工作中的编译环境,免去我敲命令行所浪费的时间,我个人写了一个非常有用而又简单的脚本框架,该框架即可以完成的工程源码编译,也可以清除,拷贝等等操作,具体需要开发者自己来实现细节,我的框架思 ...
随机推荐
- c/c++:带有返回类型的函数没有return语句会怎么样?
c/c++:带有返回类型的函数没有return语句会怎么样 背景 机器有时候启动的时候发现异常,跟踪了代码发现,有人在写一个int函数的时候,有一个分支没有return: 参考:https://www ...
- 海思SDK 学习 :001-HI_SDK 的 安装
背景 保密.不管怎么样接触到了海思SDK的开发,作为一项比较常见的技术,我们开展有关地学习. host平台 :Ubuntu 16.04 arm平台 : 3531d arm-gcc :4.9.4 概况 ...
- 记一次难忘的json反序列化问题排查经历
前言 最近我在做知识星球中的商品秒杀系统,昨天遇到了一个诡异的json反序列化问题,感觉挺有意思的,现在拿出来跟大家一起分享一下,希望对你会有所帮助. 案发现场 我最近在做知识星球中的商品秒杀系统,写 ...
- 使用Stream流实现以List<Map<String, Object>>集合中Map的key值进行排序
使用Stream流实现以List<Map<String, Object>>集合中Map的key值进行排序 创建一个list存入数据 List<Map<String, ...
- vulnhub - hackme1
vulnhub - hackme1 信息收集 端口扫描 详细扫描 目录扫描跟漏洞探测没发现什么可用信息,除了登录还有一个uploads目录应该是进入后台之后才能使用 web主页是个登录注册页面,爆了一 ...
- Spring Cloud 比较
Spring Cloud 比较 一.简介 1.SpringCloud:一套微服务架构下的一站式解决方案,理念就是解决我们在微服务架构中遇到的任何问题: 2.SpringCloudAlibaba:阿里实 ...
- 如何在 Vue 项目中优雅地使用图标
1. 字体图标与矢量图标 目前主要有两种图标类型:字体图标和矢量图标. 字体图标是在网页打开时,下载一整个图标库,通常可以通过特定标签例如 <i> 来使用,优点是方便地实现文字混排,缺点是 ...
- [oeasy]python0140_导入_import_from_as_namespace_
导入import 回忆上次内容 上次学习了 try except 注意要点 半角冒号 缩进 输出错误信息 有错就报告 不要隐瞒 否则找不到出错位置 还可以用traceback把 系统报错信息原 ...
- [oeasy]python0045_转化为10进制数_int_integrate_integer_entire_整数
转化为10进制 回忆上次内容 上这次总结了四种进制 函数名 对应单词 进制类型 数字事例 前缀 bin() binary 2 0b1100001 0b oct() octal 8 0o141 0o h ...
- electron安装成功记录
1.登录官网查看当前最新版本对应的node,注意这里不要看php那个汉化的,他那个是老版本的,node对不上 2.nvm安装一个新的node 3.使用cnpm安装(npm安装还是报错了,记得删node ...