Operating System - HP-UX
1753769 Members
5364 Online
54796 Solutions
New Discussion юеВ

Stuck with shell scripting...

 
SOLVED
Go to solution
mpua
Frequent Advisor

Stuck with shell scripting...

Hi, Im trying to write a shell script that performs the following actions:

- Check in a given directory how many occurrences of a file called server* (the * representes a date, obviously different for each file).

- Leave untouched the two more recent server* entries and delete the older.

How can be that done?

Regards.
7 REPLIES 7
jack challen_1
Advisor
Solution

Re: Stuck with shell scripting...


===
NUMFILES=$(ls server* | wc -l)
STARTLINE=$(expr $NUMFILES - 2)
ls server* | sed -n "$STARTLINE,\$p" | xargs echo rm
===

That'll only echo the "rm" commands; remove the word "echo" if you're happy with the results of that test.
Dennis Handly
Acclaimed Contributor

Re: Stuck with shell scripting...

By "recent" do you mean by last modification or do you mean a date encoded in the filename?

If it is by last modification, you could do:
ll -rt server* | tail -n +3
(This should give you the ones to remove.)
jack challen_1
Advisor

Re: Stuck with shell scripting...

Ah yes. "tail", I forgot that... whoops.
muruganantham raju
Valued Contributor

Re: Stuck with shell scripting...

Hi,
Following command remove everything except recent two entries.
# ls -lt server* | rm `awk ' NR > 3 { print $NF }'`

HTH
Muru
Dennis Handly
Acclaimed Contributor

Re: Stuck with shell scripting...

>Muru: Following command remove everything except recent two entries.
> ls -lt server* | rm $(awk 'NR > 3 { print $NF }')

Your edge arithmetic is off by one, you need: NR > 2
mpua
Frequent Advisor

Re: Stuck with shell scripting...

Hi again,

I mean modification time.
The tail and awk code you gave to me prints (or removes, in this case) the two more recent items of server*.
Is there any way of printing (in my case, removing) every server* occurrence EXCEPT the two more recent ones?
mpua
Frequent Advisor

Re: Stuck with shell scripting...

I made a mistake and introduced the "-r" in the ls command. Its my fault :D. The code works perfect for what i was looking for.

Thanks you so much!