shell下格式化輸出為表格樣式
阿新 • • 發佈:2022-04-15
shell輸出格式化為表格樣式,過程如下:
1 +#+#+#+ + + + + +----+----------+-----+ 2 id name age |id#|name#|age#| |id |name |age | |id |name |age | 3 => +#+#+#+ => + + + + => +----+----------+-----+ 41 HuYang 17 |1#|HuYang#|17#| |1 |HuYang |17 | |1 |HuYang |17 | 5 2 ZhangSan 23 |2#|ZhangSan#|23#| |2 |ZhangSan |23 | |2 |ZhangSan |23 | 6 +#+#+#+ + + + + +----+----------+-----+
完整程式碼:
#!/bin/bash # definite a separation separation="#" # set title function set_title(){ title="" column_count=0 for column in "$@" do title+="|${column}${separation}" let column_count++ done title+="|\n" } # seg function set_segmentation(){ seg="" for i in $(seq ${column_count})do seg+="+${separation}" done seg+="+\n" } # set content function set_content(){ content="" for i in $@ do content+=`set_line ${i//","/" "}` done } # set line function set_line(){ local line="" for i in $@ do line+="|${i}${separation}" done line+="|\n" echo ${line} } function output_table() { set_title id name age set_segmentation set_content "1,HuYang,17 2,ZhangSan,23" table=${seg}${title}${seg}${content}${seg} echo -e ${table}|column -s "${separation}" -t|awk '{if($0 ~ /^+/){gsub(" ","-",$0);print $0}else{gsub("\\(\\*\\)","\033[31m(*)\033[0m",$0);print $0}}' } output_table