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

使用Awk匹配untagged行后替换后续短横线行首内容并输出

解决方案:用Awk实现文本替换需求

核心思路

  1. 遍历每一行,捕获包含"untagged"的行的第一个字段并存储为变量,遇到这类行直接跳过输出。
  2. 匹配到以短横线-开头的行时,将第一个字段替换为之前捕获的字段值,然后输出处理后的行。
  3. 非目标行直接忽略。

可行的Awk代码

/untagged/ { tag = $1; next }
/^-/ { $1 = tag; print }

代码解释

  • /untagged/ { tag = $1; next }:匹配到含"untagged"的行时,把该行第一个字段存入tag变量,next跳过后续逻辑,避免输出该行。
  • /^-/ { $1 = tag; print }:匹配到以-开头的行时,替换第一个字段为tag的值,打印处理后的整行。

示例验证

输入示例

foo123 untagged some other text
- item1 details here
- item2 more details
bar456 untagged another line
- item3 info
- item4 extra info
- item5 end

处理后输出

foo123 item1 details here
foo123 item2 more details
bar456 item3 info
bar456 item4 extra info
bar456 item5 end

该代码可适配后续-开头行数为2-9行的场景,完全满足需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.11 20:32:32