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

sed首行匹配指定字符串时首尾插入行失败的问题排查

解决sed仅插入顶部行、底部行未生效的问题

Hey Mario, let's break down why your bottom line isn't being inserted, and fix it up!

问题根源

Your original sed command uses 1!b in the first script block:

sed -e '1!b;/REMARK/i MODEL 1' -e '$ a ENDMODEL ' file.txt

The 1!b means: "for every line except the first, jump to the end of the script (so skip all subsequent commands)". That means the second -e '$a ENDMODEL' never runs for any lines after the first. And since the first line isn't the last line of your file, the $a command (which only triggers on the last line) never gets executed at all.

正确解决方案

Since your goal is to only insert the top and bottom lines if the first line matches REMARK, here are a couple of solid approaches:

方法1:简洁的条件分支(推荐)

This clean approach only runs the insert commands if the first line matches your pattern:

sed -e '1{/^REMARK/!b}' -e 'i MODEL 1' -e '$a ENDMODEL' file.txt

Here's how it works step-by-step:

  • 1{/^REMARK/!b}: On the first line only, if it doesn't start with REMARK, jump to the end of the script (so no changes are made to the file). If it does match, we continue executing the rest of the commands.
  • i MODEL 1: Inserts MODEL 1 before the first line (only runs if the first line matched).
  • $a ENDMODEL: Appends ENDMODEL to the last line of the file (again, only runs if the first line matched, since we didn't jump to the end).

方法2:使用hold空间标记匹配状态

If you want a more explicit way to track the match state, this version uses sed's hold space to remember if the first line matched:

sed '1{/^REMARK/{i MODEL 1; h;};}; ${x; /REMARK/{a ENDMODEL}; x;}; p' file.txt

Breakdown:

  • 1{/^REMARK/{i MODEL 1; h;};}: On the first line, if it starts with REMARK, insert MODEL 1 then save the line to the hold space (our "match flag").
  • ${x; /REMARK/{a ENDMODEL}; x;}: On the last line, swap the hold space into the pattern space. If it contains REMARK, append ENDMODEL, then swap back to the original last line.
  • p: Print every line normally.

测试结果

For your test file file.txt:

REMARK Blah Blah blah

Running the recommended command will output:

MODEL 1
REMARK Blah Blah blah
ENDMODEL

If the first line didn't match REMARK, the file would be output exactly as-is, with no inserts.

内容的提问来源于stack exchange,提问作者Mario A Bianchet

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:05:12