using sed

Jerry Peek jdpeek at rodan.acs.syr.edu
Mon Dec 11 03:09:19 AEST 1989


In article <14404 at eerie.acsu.Buffalo.EDU> kwon at sybil.cs.Buffalo.EDU (Thomas Kwon) writes:
> I'm a novice hacker who is trying to use 'sed' to extract "certain
> string" of "certain column" of "certain line" of a result of a "certain
> command". 
> Since that sounds too confusing, here is what I really mean. By typing
> 'ruptime' at the prompt, I get something like the following :
> 
>   antares       up 21+04:15,     4 users,  load 1.36, 1.50, 1.29
>   castor        up  1+05:20,     0 users,  load 0.00, 0.00, 0.00
>   deneb         up 42+23:50,     0 users,  load 0.00, 0.00, 0.00
>   gort          up 14+14:47,    21 users,  load 2.48, 1.77, 1.59
>   joey          up 14+14:42,     2 users,  load 0.00, 0.05, 0.26
>   marvin        up 14+15:03,    10 users,  load 1.43, 1.34, 1.12
>   sybil         up 14+11:28,    33 users,  load 2.83, 2.93, 2.44
>   wolf          up 70+20:41,     0 users,  load 1.46, 1.49, 1.28
> 
> I want to extract the string "1.34" which is in "column 8" of "line 6"
> and set that to a variable. How can this be done?

It depends on how "ruptime" formats its output -- if a load average number is
over 9.99, is there still a leading space?  The way I've done it "plays safe"
by including all text between the two commas, with the leading space:

   marvin        up 14+15:03,    10 users,  load 1.43, 1.34, 1.12
						      ^^^^^

Here's the line I came up with:

	set load=`ruptime | sed -n '6s/^.*load[^,]*,\([^,]*\).*/\1/p'`

In English, that reads:
        -n              Don't print any line unless I give the "p" command
        6s/             On line 6, substitute...
        ^.*load[^,]*,   Everything up to and including the first comma (,)
                        after the word "load"
        \([^,]*\)       Save everything up to but not including the next
                        comma in the tagged field 1
        .*              The rest of the line
        /\1/            Replace all that stuff (the entire line) with the
                        contents of tagged field 1
        p               Print this line

If you'd rather have the line that contains the word "marvin" instead
of the 6th line, the sed expression should look like this:

    set load=`ruptime | sed -n '/marvin/s/^.*load[^,]*,\([^,]*\).*/\1/p'`

I'm no expert, but I think "sed" is great -- fast and flexible, just cryptic.
Maybe Randall and I should have a perl-vs.-sed showdown. :-) :-)

--Jerry Peek; Syracuse University Academic Computing Services; Syracuse, NY
  jdpeek at rodan.acs.syr.edu, JDPEEK at SUNRISE.BITNET        +1 315 443-3995



More information about the Comp.unix.questions mailing list