You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用AWK处理Zsh脚本输出:数据库计数结果格式化需求

问题:格式化Zsh脚本输出的数据库计数结果

我有一个Zsh Shell脚本,输出包含数据库计数结果,同时夹杂常规文本:

Regular lines of output that should be ignored.
+-----------------------------------------+
| rowcount.account_config records deleted |
+-----------------------------------------+
|                                       2 |
+-----------------------------------------+
+----------------------------------------+
| rowcount.accounts_user records deleted |
+----------------------------------------+
|                                      2 |
+----------------------------------------+

希望将其转换为以下格式:

Regular lines of output that should be ignored.
- account_config records deleted: 2
- accounts_user records deleted: 2

初始尝试及问题

我尝试了以下命令:

functionThatOutputsText | awk -F '|' '/rowcount\./ {print "- " $2 ": " $NF}'

但输出不符合预期,结果如下:

-  rowcount.account_config records deleted : 
-  rowcount.accounts_user records deleted : 

解决方法1:sed+awk组合处理输出

更新于2024年5月28日 09:30:24

采用方案并稍作调整,先通过sed移除输出中的rowcount.,再用awk处理格式:

functionThatOutputsText | sed -e 's/rowcount.//' | awk -v OFS=": " '/^\|.*\|$/ {
  if(p) { print "- " p, $2; p="" }
  else { p=substr($0, 3, length($0)-4) }
  next }
/^\+-*\+$/ { next } 1' 

该命令可以得到预期结果:

Regular lines of output that should be ignored.
- account_config records deleted: 2
- accounts_user records deleted: 2

注:由于我可以控制原脚本,也可直接在输出中移除rowcount.,原本添加它是为了标记需要处理的行。


解决方法2:修改MySQL查询格式后处理

参考建议,修改MySQL查询语句:
原查询:

SELECT ROW_COUNT() as 'rowcount.account_config records deleted';

修改为:

SELECT ROW_COUNT() as 'rowcount.account_config records deleted'\G

此时计数输出变为:

*************************** 1. row ***************************
rowcount.account_config records deleted: 2
*************************** 1. row ***************************
rowcount.accounts_user records deleted: 2

再调整处理脚本:

functionThatOutputsText | grep -Ev '[*]{3,}' | sed -e 's/rowcount./- /'

该方案同样能得到预期输出。


内容的提问来源于stack exchange,提问作者Robert Mark Bram

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 06:21:08