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

如何用awk将树形三类多行模式转置为目标单行格式?

树形文本转置为单行格式

输入文本

listb: harold newu/edu
  tag: 05.8s
    step: sha256asd6f4, size: 1024
    step: sha256asd6f5, size: 1024
  tag: 06.8s
    step: sha256asd6f8, size: 1024

listb: break version
  tag: 05.8s
    step: sha256asd6c5, size: 720

listb: version/test
  not exist

期望输出

listb: harold newu/edu tag: 05.8s step: sha256asd6f4, size: 1024
listb: harold newu/edu tag: 05.8s step: sha256asd6f5, size: 1024
listb: harold newu/edu tag: 06.8s step: sha256asd6f8, size: 1024
listb: break version  tag: 05.8s step: sha256asd6c5, size: 720
listb: version/test not exist

解决方案(AWK脚本)

以下AWK脚本可处理三级层级结构及特殊场景:

/^listb:/ {
    listb = $0
    tag = ""
    next
}
/^  tag:/ {
    tag = substr($0, 3)
    next
}
/^    step:/ {
    step = substr($0, 5)
    print listb, tag, step
    next
}
/^  not exist/ {
    print listb, substr($0, 3)
    next
}

使用方式

将脚本保存为transpose.awk,执行命令:

awk -f transpose.awk 输入文件名

脚本逻辑

  • 匹配listb:行时,记录内容并重置标签变量;
  • 匹配tag:行时,去除前置空格后记录标签内容;
  • 匹配step:行时,去除前置空格后拼接所有层级内容输出;
  • 匹配not exist行时,直接拼接主项内容输出。

内容的提问来源于stack exchange,提问作者da4fdsa6

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 05:47:17