如何用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
相关产品推荐
相关产品推荐

