7/1 Using sed, how do I do the following? I want to replace the
first line containing a particular pattern with the 2nd line
containing said pattern. For example, if "line" is the pattern,
then I want
this is the 1st line
this is the 2nd
this is the 3rd
this is the 4th line
to become
this is the 4th line
this is the 2nd
this is the 3rd
this is the 1st line (Actually, I don't care if this line
shows up like this or gets deleted.)
\_ stupid to do this in sed. use perl.
\_ OK, how do I do this in perl?
\_ while ( $line = <> ){
if ( $line !~ /line/ ) {
$output[$count++]=$line;
next;
}
if ( ! $firstline ) {
$firstline = $line;
$firstindex = $count++;
} else {
$output[$firstindex]=$line;
$output[$count++]=$firstline;
}
}
print foreach @output;
# (Approximately) -tom
\_ You don't need the "foreach"
\_ Just for fun, how can this be done using sed?
\_ sed is short for "stream editor". It's designed to look at
the input one line at a time. making it handle line operations
is unholy, and possibly illegal in most states.
\_ there is nothing fun about doing this in sed. -tom
\_ lots of things can be fun if you're avoiding more important
work. here it is:
sed -e '/line/\!bS;:M;$\!N;s/\n.*line/&/;tE;$\!bM;:E;s/^\([^\n]*\)\(\n.
*\n\)\([^\n]*\)$/\3\2\1/;:S'
this swaps the 2N-1'th and the 2N'th lines matching "line"
for all possible N. if there is an odd number of such
lines, the last one is left in place. note that the
3 "!"'s are \-escaped for tcsh; your shell might
differ. naturally, s/line/foo/g to change pattern.
tested on gnu sed 3.02. inserting a few newlines will
make this work on soda's sed as well:
sed -e '/line/\!bS\
:M\
$\!N;s/\n.*line/&/;tE\
$\!bM\
:E\
s/^\([^\n]*\)\(\n.*\n\)\([^\n]*\)$/\3\2\1/;\
:S'
-alexf
\_ alexf = leet sed god
\_ s/leet sed god/bored new sed user/ -alexf
\_ sed rules!!!
\-first, i probably wouldnt do this in sed either.
it may be doable in sed but your description isnt
complete, so i cant suggest a solution. do you just
want to *swap* 1st match of regexp with second match
of regexp? finally, sed can certainly do non-line
based things more easily than say grep. see e.g.
the , operator. --psb
\_ I want the first line that matches regexp to
be replaced with the 2nd line that contains
regexp. The entire line need not match regexp,
but only contain it. But I want the entire
first line (that contains a match to regexp) to
be essentially overwritten by the next line that
contains a match to regexp. -op
\_ rpn calculator written in sed:
http://sed.sourceforge.net/local/scripts/dc.sed.html
\_ just curious, why do you want to do this? seems kinda weird.
\_ he's trying to troll ilyas into writing it in ocaml |