首页 > 其他分享 >一个能够生成 Markdown 表格的 Bash 脚本

一个能够生成 Markdown 表格的 Bash 脚本

时间:2024-08-22 10:07:50浏览次数:2  
标签:markdown 表格 -- col Markdown table Heading 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,表格,--,col,Markdown,table,Heading,Bash
From: https://www.cnblogs.com/edisonfish/p/18373149

相关文章

  • Markdown语法学习
    Markdown语法学习标题一级标题二级标题三级标题四级标题……字体HelloworldHelloworldHelloworldHelloworld引用Helloworld引用分割线Helloworld图片超链接网页列表ABC注意在输入(''*.'或'-'后接'')AC表格名字性别生日......
  • ant design vue 表格table 和复选框Checkbox结合 实现树形数据操作
    前言:最近在做一个权限管理的页面,需要配置权限。业务给的要求在表格里,展示权限以及编辑权限。然后根据权限数组,动态展示模块。页面需求:可以设定每个公司或者部门的单独权限,可以编辑保存权限主要实现:1.全选,反选(递归循环,every,some实现)2.子级选中其父级选中,父级取消子级也取消3.......
  • MarkDown基础及表格、KaTeX公式、矩阵、流程图、UML图、甘特图语法
    概述最多可设置6级标题技巧列表有序列表MD语法:1.你好2.我也好呈现效果:你好我也好无序列表MD语法:-a-b*aa*bb+aaa+bbb效果:abaabbaaabbb结论,支持三种方式:-、*、+TODO列表MD语法:-[x]后端接口开发-[]与前端联调呈现效果:后端......
  • 表格单元格点击操作(弹窗)
    表格点击单元格出现弹窗<el-tableref="table":data="tableList"row-key="tableId"@row-click="handleRowClick"><el-table-columnlabel="列1"p......
  • Markdown书写规范
    书写规范MD001-Headinglevelsshouldonlyincrementbyonelevelatati-Me标题级数只能每次扩大一个,也就是说不能隔级创建标题,必须h1-h2-h3…这样MD002-Firstheadingshouldbeatoplevelheading文档的第一个标题必须是最高级的标题,也就是h1MD003-Head......
  • 在 markdown 中运行代码片段
    本篇文章将分享一种可以在markdown中运行代码片段的方案达到的效果实施步骤安装VsCode和MarkdownPriviewEnhanced插件从VisualStudioCode这里下载安装Vscode从Vscode中安装MarkdownPriviewEnhanced插件将MarkdownPriviewEnhanced插件设置中的Ena......
  • ace markdown editor 原生web components
    src/index.html:<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width,initial-scale=1.0"><title>Document&......
  • 表格控件:计算引擎、报表、集算表
    近日,葡萄城正式发布了SpreadJS最新版本V17.1,为前端表格控件市场带来了一系列令人瞩目的新特性和功能增强。本次更新旨在进一步提升用户在计算引擎、报表生成和分析等方面的体验,为各行业的开发者提供更强大的工具支持。主要更新亮点工作薄增强居右对齐将样式的textDirection......
  • 不同矩阵变换的特征值和特征向量对比,简洁明了的大表格!
    为了方便自己,也为了方便大家总结如图,毫无废话,原矩阵为A矩阵特征值特征向量----如有错误还请告知,觉得很对欢迎点赞!......
  • 学习 node.js 六 Markdown 转为 html,zlib
    目录Markdown转为html安装ejs语法标签含义 1.纯文本标签2.输出经过HTML转义的内容3.输出非转义的内容(原始内容)markedbrowserSynczlibgzipdeflategzip和deflate区别http请求压缩 Markdown转为html什么是markdown?Markdown是一种轻量级标记......