[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: keeping the two latest files on a folder



Hello,
Andrew Sackville-West skrev:
> On Tue, Oct 13, 2009 at 06:46:31PM -0400, Chris Jones wrote:
>
>> On Tue, Oct 13, 2009 at 03:35:19PM EDT, Håkon Alstadheim wrote:
>>
>>> Israel Garcia skrev:
>>>
>>>> Hi List,
>>>>
>>>> It's a simple question but difficult to me :-).
>>>>
>>>> How can I delete all files on a folder /xxxx but keeping only the two
>>>> latest (newest) files?
>>>>
>>>>
>>>>
>>> untested, run it with 'echo' in front first to test:
>>> rm $(ls -rt | sed '1,2d')
>>>
>> sed rocks...!
>>
>
>
> indeed. wow.
>
> A
>
Due to all the positive feed-back, I actually tested the "ls -rt"-bit,
and sure enough, the 'r' makes ls list the newest files _last_, so you
DON'T want 'r'. This makes the correct command:

rm $(ls -t | sed '1,2d')


You should _still_ test it first using 'echo ', to make sure there are no subdirectories in there, and on general principles. Adapt to whatever you have in the directory.

Using the find command ensures that directories are skipped. The -maxdepth 0 restricts the search to the current directory:

   rm $(find . -maxdepth 0 -type f | xargs ls -t| sed 1,2d)

However, this does not work, if you have files with spaces! Then the best is to use the -print0 and xargs -0 that uses zero-delimited strings instead of space delited strings. Also the rm must be run in a loop and with quotation marks around the filename:

    find . -maxdepth 0 -type f -print0 | xargs -0 ls -t| sed 1,2d | while read f; do rm -f "$f" ; done

BR,
Roland





--
To UNSUBSCRIBE, email to debian-user-REQUEST@lists.debian.org
with a subject of "unsubscribe". Trouble? Contact listmaster@lists.debian.org



--
GRATIS für alle GMX-Mitglieder: Die maxdome Movie-FLAT!
Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01

Reply to: