Problem using multiple 'head' commands in shell script

Tom Christiansen tchrist at convex.COM
Thu Jan 31 05:26:29 AEST 1991


>From the keyboard of krs at amdahl.uts.amdahl.com (Kris Stephens [Hail Eris!]):
:In article <6925 at exodus.Eng.Sun.COM> mcgrew at ichthous.Eng.Sun.COM (Darin McGrew) writes:
:>In article <1671 at abekrd.UUCP> garyb at abekrd.UUCP (Gary Bartlett) writes:
:>->Can someone explain to me what is happening with the following Bourne shell
:>->script and more importantly how I can get around it:
:>->
:>->	#!/bin/sh
:>->	cat file | (
:>->		head -200
:>->		echo "Line 201 follows"
:>->		head -200
:>->		echo "Line 401 follows"
:>->		cat
:>->	)
:>->
:>->...

:If, however, the    echo "Line ?01 follows"    in the original example
:was a place holder for "I want to do other stuff here, then pick up
:processing with the next set of lines", neither the awk nor the sed
:calls will allow it, as both simply insert the line-counting messages
:into the stream of data from file.
:
:Dog slow though it be, the following will do it:

I really wasn't going to do this, but once I saw things like "dog slow"
and "shell functions" (which many of us don't have) and "mayhem will
result", I just couldn't not give a perl solution.

    while (<>) {		# fetch line into pattern space
	if ($. < 201) {
	    s/foo/bar/g;	# do some other stuff
	} elsif ($. < 401) {
	    tr/a-z/A-Z/;	# do other stuff
	} else {
	    print "line number is $., continuing...\n"; # do final stuff
	} 
    } 

Basically, perl keeps track of your current input line number in the $.
variable (mnemonic: think of dot in editors) just as awk does with NR.
The advantage to using perl is that you can do much more without having to
call other program, and instead of asking yourself a load of questions
like "does their awk have functions?", "does their sh have functions?",
"did I exceed awk/sh's field limits?", you only have the one question of
whether perl is on the system, and unlike nawk and ksh (although like gawk
and bash), you can put it on your system without shelling out money if the
answer should be no.  You'll also find that perl will be faster than
the sed/sh/awk combo, and often faster than even just one of them.

Please, save the flames for alt.religion.computers.  I'm just trying
to present another possibility of which the original poster may not
have been aware.

--tom
--
"Hey, did you hear Stallman has replaced /vmunix with /vmunix.el?  Now
 he can finally have the whole O/S built-in to his editor like he
 always wanted!" --me (Tom Christiansen <tchrist at convex.com>)



More information about the Comp.unix.shell mailing list