Re: sed for sequential lines
- From: Logan Shaw <lshaw-usenet@xxxxxxxxxxxxx>
- Date: Thu, 27 Mar 2008 21:07:29 -0500
Travis wrote:
On Mar 26, 6:14 pm, Logan Shaw <lshaw-use...@xxxxxxxxxxxxx> wrote:Rainer Weikusat wrote:Travis <travis.bow...@xxxxxxxxx> writes:I have a file like this
print "condition 1 has happened"
exit
I would like to sed (or maybe perl?) for the line "print "condition 1
has happened"" and replace exit with #exit (commenting it out).
Actually, you could do it in Perl with a similar amount of effort:
perl -p -e '
if (/^print "condition 1 has happened"/ .. /^exit/)
{ s/^exit/#exit/; }'
Or slightly more cryptically:
perl -p -e '/^print "condition 1 has happened"/ .. s/^exit/#exit/'
The '..' operator is a state machine which enters an "on" state
once the first argument is true and remains in that state until
the second argument is true. That's perfect for remembering
line-oriented context, which is not surprising since AFAIK that's
what the operator was created for.
what about a wildcard? Like saying catch all the lines that start
print "condition..." and commenting out the exit in the following
line?
In the above perl code, the things between the slashes are regular
expressions matching against lines in the file. So you just need
to change to a regular expression that matches any line beginning
with 'print "condition':
/^print "condition"/
The resulting Perl code would be this:
perl -p -e '/^print "condition"/ .. s/^exit/#exit/'
If you'd like to be a little stricter and allow lines like
'print "condition N has happened"' (where "N" stands for a
number), you just need to use a regular expression that
contains a pattern matching any number (actually, any sequence
of digits):
perl -p -e '/^print "condition" \d+ has happened"/ .. s/^exit/#exit/'
Usually, when doing this type of stuff, I would try to be liberal
and recognize any amount of whitespace, so that the "print" can be
indented:
perl -p -e '/^\s*print\s*"condition\s+\d+\s+has\s+happened"/
.. s/^exit/#exit/'
Every "\s*" will match zero or more whitespace characters, and
every "\s+" will match one or more of them.
- Logan
.
- References:
- sed for sequential lines
- From: Travis
- Re: sed for sequential lines
- From: Rainer Weikusat
- Re: sed for sequential lines
- From: Logan Shaw
- Re: sed for sequential lines
- From: Travis
- sed for sequential lines
- Prev by Date: Re: sed for sequential lines
- Next by Date: Re: Interpreting program core dump in mdb
- Previous by thread: Re: sed for sequential lines
- Next by thread: System Calls and I/O Parameter Reinitialization
- Index(es):
Relevant Pages
|