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 withREMARK, 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: InsertsMODEL 1before the first line (only runs if the first line matched).$a ENDMODEL: AppendsENDMODELto 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 withREMARK, insertMODEL 1then 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 containsREMARK, appendENDMODEL, 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

