While loop depends on variable

The variable N is set upon start of script so while loop runs and keeps running because N is not being updated when loop is running:

N becomes less than 9 but it still runs (should be "done")....

Any ideas? Thanks!

N=`wc -l /home/count.txt | awk '{print $1}'`

while test "$N" -gt "10"
do
sed -i "1,1 d" /home/count.txt
done

You need to decrement the variable. Assuming ksh or bash and using your example:

N=`wc -l /home/count.txt | awk '{print $1}'`

while test "$N" -gt "10"
do
    echo "something"
    ((  n-- ))
done

If you are using a shell that doesn't support the (( expression )) syntax you'll need to replace that with the proper statement that decrements N.

You could also do:

N=`wc -l /home/count.txt | awk '{print $1}'`
[ $N -gt 10 ] && sed "1,$((N-10))d" /home/count.txt

or

tail -10 /home/count.txt > /tmp/trim.$$
mv /tmp/trim.$$ /home/count.txt

Do this to save a process (awk) by not having wc print the filename in the first place, assuming your shell supports typeset:

typeset -i N  ## define N as an integer (strips out the leading whitespace from wc)
N=`wc -l < /home/count.txt`

Combining some of the ideas above we can condense the script to:

while test $(wc -l < /home/count.txt) -gt 10
do
        sed -i "1,1 d" /home/count.txt
done

Which most would write as:

while [ $(wc -l < /home/count.txt) -gt 10 ]
do
        sed -i "1,1 d" /home/count.txt
done

Note the numeric compare -gt (no quotes).

I'd probably do it without the while:

sed -i "1,$(( $(wc -l <file) - 10 ))d" file

@agama
I can't try your code because I don't have sed -i but the code looks good and efficient.

Reading between the lines the O/P posted code which should remove a line from a file one-line-at-a-time until it reached the required number of lines. Obviously an academic (or homework?) problem because there are much easier ways of achieving the final result, but agama's solution is really good.

It's been fun.

@Methyl -- It seemed a waste starting n-10 processes just to remove the first line of a file. I didn't do any experiments, but with the -i option I would assume that sed then writes n-1 lines to a tmp file and does a rename. That's lots of I/O that isn't necessary since it can be done with just two passes.

I tend not to use -i, as you point out it's less portable, and if writing for greater portability (assuming modern shell) might do it this way:

sed  "1,$(( $(wc -l <file) - 10 ))d" file >file.new && mv file.new file

Thanks, really good suggestions/examples in this thread. This is not for homework but an actual script I am doing.

Still think my solutions are better, particularly in the case where file has less than 10 lines!

True -- the assumption like I made that there'd always be 10 lines is the kind that will bite you at 3 in the morning.