Delete # of Lines after counting

I'm trying to write a script to clean up log file automatically when it reaches 1000 lines. I can't get this to work..can some help me please :slight_smile:
Server: SunOS 5.8 Generic_117350-53 sun4u sparc SUNW,Netra-T12

#!/bin/ksh

#file reference
file=`echo "$HOME/support/moe/b.tc"`

#linecount
linecount=`wc -l $file | awk '{print $1}'`
echo "Line count before : $linecount"

#find and delete lines greater than 1000
if [$linecount -gt 1000]; then
sed -i '1,100d' $file
else
echo " line count is file"
fi

echo $linecount
echo "Line count in the file is:  `wc -l $file | awk '{print $1}'`"

:mad:

Somthing like this ? (remove the 100 first line of the log if it gets greater or equal to 1000 lines)

if [[ $( wc -l $file ) -ge 1000 ]]
then
    tail +101 $file >log.tmp
    cat log.tmp >$file
    rm log.tmp
fi

hmmm.. still having some issues maybe u can see what could it be :

#!/bin/ksh

#file reference
file="b.tc"

#linecount
linecount=`wc -l $file | awk '{print $1}'`
echo "Line count before : $linecount"

#find and delete lines greater than 1000
if [[ $( wc -l $file ) -ge 1000 ]] && tail +101 $file >log.tmp
cat log.tmp >$file
rm log.tmp
else
echo " line count is file"
fi

echo $linecount
echo "Line count in the file is:  `wc -l b.tc | awk '{print $1}'`"



"h.sh" 19 lines, 388 characters 
romtst2@towgd20 UAT  /spectra/romtst2/support/moe > h.sh
Line count before : 13626
h.sh[11]: syntax error at line 15 : `else' unexpected

I'm not sure of your syntax here. We have an if without a then but using && instead and I'm not sure what else will get processed. You may just career on into the cat log.tmp>$file hence why the failure at the else statement.

Consider this:-

if [ `wc -l $file` ]
then
   tail +101 $file > log.tmp
   mv log.tmp $file
else
   echo "Line count of $file is `wc -l $file`"
fi

I hope that this helps.
Robin

1 Like

Thanks that worked just fine :slight_smile:

You are welcome.

Robin
Liverpool
UK

  1. You are true, i fixed my code with the if then instead of &&.

  2. My turn now... :wink: ... WARNING about your code :

a) if [ `wc -l $file` ] : this doesn't check whether is exceed 1000 lines

b) by using mv log.tmp $file , you will loose the inode of $file !!!!

this mean that if the logfile is currently being processed you may encounter unexpected behaviour or errors.
That is the reason why it is advisable to use

cat log.tmp >$file 
rm log.tmp

instead of mv log.tmp $file

2 Likes

ctsgnb & Robin thanks guys..u guys are great..
my code worked fine just had to tweak it up a bit...i'll take that cat suggestion..didn't think about thanks to both of u :slight_smile: Moe