Re: How to use sed to remove a line from a cron file and also remove all commented lines directly above it

'Cameron Simpson' <[email protected]>
Newsgroups gmane.editors.sed.user
Message-ID <[email protected]>
On 09Jul2012 19:11, Van Handel <[email protected]> wrote:
| Thanks for the answer.  I'll start trying these things.
| One thing that seems unclear, in my example I wanted to remove from
| the line beginning with
| # Purge
| but in general, I want to remove the line matching the command pattern specified,
| along with any commented lines directly above that.  For example, a cron file
| might have some commands and commented lines in it, followed by 5 commented lines,
| followed by a line with the specified pattern, followed by some more lines that
| could be comments or commands.
| 
| I want to remove the matching command line and the 5 commented lines above it,
| but as soon as a line above it is not a comment, stop deleting lines.
| This one has me confused because I know I need to store commented lines until
| I see a non-commented line that contains the specified pattern (which could
| possibly mean storing 0 commented lines and the specified command line), and
| then delete those lines.

Please don't top post. Reply below quited text and trim the irrelevant
bits. Thanks.

This is a classic example use for the "hold" space. Sed has two buffers:
the current pattern space (normally the current line under
consideration) and the "hold" space. You can save lines to the hold
space (H), replace the holdspace with the current line (h) and swap the hold
space for the current line (x).

So for your example you'd write a script that saved lines to the hold
space, delete the current line and looped. Until the current line
matched your command pattern or a non-comment. Then consider things; if
it is the command pattern, discard the current line and load the next
line. Otherwise print the hold space and the current line and begin
anew. In this way you gather up the preceding comment for saving or
discarding.

Something like this (totally untested again):

  # comment? accrue into the hold space and go to the next line
  /^#/{ H; d; }

  # your target cron line?
  # wipe line, exchange for hold space (puts empty line into hold
  # space), delete (advance to next line)
  /^[^#].*your command string here/{ s/.*//; x; d; }

  # not a comment or the target line?
  # print hold space, print line, continue
  x
  p
  x

Cheers,
-- 
Cameron Simpson <[email protected]>

Pessimism, n.  A philosophy forced on the convictions of the observer by the
disheartening prevalence of the optimist with his scarecrow hope and his
unsightly smile.
Ambrose Bierce (1842-1914), U.S. author. The Devil's Dictionary (1881-1906).
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.