logo       

Re: sed one-liner?: msg#00078

editors.sed.user

Subject: Re: sed one-liner?

Dear jkilbour@xxxxxxx,

Thanks for writing! On 20 Dec 2005 at 21:33, you said:

> > I decided to give it a try also. The following sed script
> > will print the penultimate line (the next to last line) on a file of
> > any length except a file which has only one line, in which case it
> > prints nothing:
> >
> > sed -e '$!{h;d;};x'
> >
> > --
> > Eric Pement
> >
>
> Could you annotate your solution a little, Eric, for those of us who
> are interested in your solution but not yet experienced enough to
> follow it?
>
> Thanks.

Your reply went to me personally, not to the sed-users mailing
list, so I'm adding the mailing list to the CC: field. Here is my
explanation:

$! { # On every line EXCEPT the last one, ..

h; # .. copy the line into the hold space, overwriting
# whatever was in there previously, and

d; # delete that line from the pattern space. As soon
# as the 'd' command is issued, sed gets a fresh line,
# puts it in the pattern space, and runs the script
# again. The result is that nothing EVER gets printed
# at all for this address range, but exactly one line
# is ALWAYS saved ... for files larger than 1 line.

}; # This brace closes the address range.

x; # To reach this command, we MUST be at the last line
# because the $!{...} portion restricted us to every line
# of the input except the last line.

# 'x' means to exchange the pattern space and the hold
# space, so whatever was on the last line of the file is
# put in the hold space, and what was in the hold space
# (which MUST have been the next-to-the-last line) is put
# into the pattern space.

# Since there are no further commands, sed prints out what
# was in the pattern space, which must be the penultimate
# line of the file. The last line of the file, which is
# still in the hold space, is not printed. Then sed exits.

Hope this helps!

--
Eric Pement - eric.pement@xxxxxxxxx
Educational Technical Services, MBI



------------------------ Yahoo! Groups Sponsor --------------------~-->
Get Bzzzy! (real tools to help you find a job). Welcome to the Sweet Life.
http://us.click.yahoo.com/KIlPFB/vlQLAA/TtwFAA/dkFolB/TM
--------------------------------------------------------------------~->

--

Yahoo! Groups Links

<*> To visit your group on the web, go to:
http://groups.yahoo.com/group/sed-users/

<*> To unsubscribe from this group, send an email to:
sed-users-unsubscribe@xxxxxxxxxxxxxxx

<*> Your use of Yahoo! Groups is subject to:
http://docs.yahoo.com/info/terms/






<Prev in Thread] Current Thread [Next in Thread>
Google Custom Search

News | FAQ | advertise