Retaining file versions based on input parameter

Hello Forum.

I have the following files in one directory:

abc_july01_2013.txt
abc_july02_2013.txt
abc_july03_2013.txt
abc_july04_2013.txt
abc_july05_2013.txt
abc_july06_2013.txt
abc_july07_2013.txt
abc_july08_2013.txt

If I want to be able to keep the last 5 versions of the file and delete the rest so that all that remains is:

abc_july04_2013.txt
abc_july05_2013.txt
abc_july06_2013.txt
abc_july07_2013.txt
abc_july08_2013.txt

Then the following code will accomplish this:

rm -f `ls -tp abc* | grep -v "/$" | awk '{ if (NR > 5) print; }'`

But I don't want to hard-code the # of versions (which is 5 in this case). I want to be able to pass in a parameter value to the command so that it's more flexible. Is there an easy way that it can be done?

Thanks

if [ -z "$1" ] 
then
        echo "Must pass in a number" >&2
        exit 1
fi

ls -tp abc* | grep -v "/$" | -v MAX="$1" awk 'NR > MAX' | xargs echo rm

Remove the echo once you've tested and are sure it does what you want.

Thank you Corona688 for your quick response.

I tried your code but I'm getting the following error:

ksh: -v:  not found.

Is that -v just before the MAX variable intentional?

Whoops, typo.

ls -tp abc* | grep -v "/$" | awk -v MAX="$1" 'NR > MAX' | xargs echo rm
1 Like

Thank you Fellow Canadian - it works beautifully. :b:

1 Like