Hi,
OS version is below.
$: uname -a
SunOS [hostname] 5.8 Generic_Virtual sun4v sparc sun4v
Unfortunately, really old version of Solaris. I've no option to upgrade, I am just a 'normal' user of the server.
Anyway, I need to process a set of files, for example, compress, gzip, rm etc. I don't need to process all files, I only need to process all but the last n files.
For example, in my script below, n is 4 and I want to do rm files except the last 4 files with filename being sorted numerically with the assumption that it is oldest to newest.
Is there a one-liner to do ls excluding the last n files similar to displaying all but last 20 lines of a log?
Script so far is below:
$: cat x.bash
#!/bin/bash
n=$( ls -1 *log | wc -l | awk '{ print $1 }' )
keep=4
let ntodo=$n-$keep
#echo $n
TODO="/bin/rm"
if [[ ${ntodo} -gt 0 ]] ; then
for log in $( ls -1 *log | sort -ta -k1.2n | head -n ${ntodo} )
do
echo "ntodo=$ntodo | ${TODO} $log"
done
else
echo "NOTHING TO ${TODO} .. ntodo=$ntodo"
fi
## ls below for sanity
echo
echo "==="
echo
ls -1 *log | sort -ta -k1.2n
Script run gives output below:
./x.bash
ntodo=6 | /bin/rm a1.log
ntodo=6 | /bin/rm a2.log
ntodo=6 | /bin/rm a3.log
ntodo=6 | /bin/rm a4.log
ntodo=6 | /bin/rm a5.log
ntodo=6 | /bin/rm a6.log
===
a1.log
a2.log
a3.log
a4.log
a5.log
a6.log
a7.log
a8.log
a9.log
a10.log
Script run output is as expected. I just want to know if there is a better way to do it or this is it.
Problem here is the ls part
ls -1 *log | sort -ta -k1.2n
This is correct only if the number of digits is 2, it is not going to be correct anymore if the number of digits changes to 3,4,5 etc So, what do I do so that the sort always gives the right result.
Several ls command gives output below and I can't get it to give the right ls to give the right sorted output hence I've used ls | sort in the script.
$: ls -1 a*log
a1.log
a10.log
a2.log
a3.log
a4.log
a5.log
a6.log
a7.log
a8.log
a9.log
$: ls -1r a*log
a9.log
a8.log
a7.log
a6.log
a5.log
a4.log
a3.log
a2.log
a10.log
a1.log
$: ls -1t a*log
a1.log
a10.log
a2.log
a3.log
a4.log
a5.log
a6.log
a7.log
a8.log
a9.log
Any guidance will be much appreciated.
BTW, the test files where created using
touch a1.log a2.log a3.log a4.log a5.log a6.log a7.log a8.log a9.log a10.log
Presumably doing ls with -t will give the right sort and it isn't? Or is that a wrong assumption?