Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hi, does anybody know how to write a script to count the number of lines in the file given as the 1st parameter on the command line,
and if this is more than 17 to display the top few and last few lines of the file to the screen, otherwise to display all the file to the screen, one page at a time.I've used the head and tale command but just couldn't get around it...
thanks

This might be what you want:
#! /bin/ksh
FILE=$1if [[ $# == 0 ]] ; then
print "Argument expected: file"
exit 1
fiif [[ ! -f $FILE ]] ; then
print "File does not exist."
exit 1
fitypeset -i LINES=`wc -l "$FILE" | awk '{print $1}'`
if (( $LINES > 17 )) ; then
head -5 $FILE #Change as needed
tail -5 $FILE #Change as needed
else
more $FILE
fi
-jim

I hope that I'm not doing your homework for you, or at least you'll take the time to learn from this if I am.
# Count the number of lines in the file
# The file is sent to wc using cat and a pipe
# because if you say "wc -l $1", you'll get
# the filename in the output also.
numLines=`cat $1 | wc -l`# Test the number of lines counted
# and issue the desired output
if [ $numLines -gt 17 ]
thenecho "First 10 lines"
head -10 $1
echo
echo
echo "Last 10 lines"
tail -10 $1else
cat $1
fi

< # because if you say "wc -l $1", you'll get
< # the filename in the output also.
< numLines=`cat $1 | wc -l`thanks for the tip there. that was bugging me when trying to figure out why the test failed before i added the '| awk'. learn something new every day.
-jim

Perfect script Don, but the only suggestion I have is to use a different tail/head number OR raise the line count specification.
Reason being, if you have a file that is 18 or 19 lines you are going to get an overlap in the display. You may also want to add a break in the head/tail to separate the two. Its purely asthetic, but will make it tons easier to read.Just my 2cp.

LanK - Good point about the line counts. I didn't think of that.
What is 'cp'?
I'm sure it's related to '2 cents', but can't figure out what 'cp' could mean. My best guess is 'copper pennies'!

![]() |
Cron daemon
|
Hp-9000 ux k200
|

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |