On 2009-11-30 at 21:20 -0500, Tom Limoncelli wrote:
> I have a file called rc-addition that contains:
> 
> 
> # BEGIN project
> a
> bunch
> of
> lines
> # END project
> 
> 
> I want to append it to the end of /etc/rc.machine but if there is already a
> "# BEGIN project" / "# END project" it should replace that text, or delete
> it and append the new text to the end.
> 
> This sounds like a job of sed but my sed fu is weak.

See, you're editing a file.  I do wonder why people fixate on stream
processing tools for editing a file, when there are command-line
interfaces available to script file-editing.  And no, {sed -i} is still
stream-orientated.

The only trick parts are:
 (1) one line, so no here-script, so need portable echo with newline
     interpretation, so use printf
 (2) A marked line disappears once deleted, so to preserve line need to
     go back one, which would fail if "# BEGIN project" is on the first
     line; thus we insert a dummy line at the start and delete it at the
     end.
 (3) For portability, putting a single-quote into the middle of a
     single-quoted string in shell requires using '"'"' -- using
     double-quotes means escaping the $ instead.  Choose your poison.

printf 'H\n1\ni\nX\n.\n$\nka\ng/^# BEGIN project$/-\\\nka\\\n+1,/^# END 
project/d\n'"'"'ar rc-addition\n1d\nw\nq\n' | ed -s /etc/rc.machine

One line, 139 characters.

136 if you remove the H\n at the start, but diagnostics are good.

All hail the one true Unix text-editor!

Regards,
-Phil
_______________________________________________
Discuss mailing list
Discuss@lopsa.org
http://lopsa.org/cgi-bin/mailman/listinfo/discuss
This list provided by the League of Professional System Administrators
 http://lopsa.org/

Reply via email to