Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I have a situation where several files may accumulate a folder for some processing and the processing routine can only handle one file at a time, and it must have a specific filename.

I need to be able to find the oldest file in this directory and rename it to the required input filename. Once processed this file gets deleted so I'd have the procedure keep renaming the oldest between processing until all files were exhausted.

e.g.:
In a folder I have:

file1 created 1 Mar
file2 created 2 Mar
file3 created 3 Mar
…

The script would have to rename the file created March 1st to 'input.dat'. On the next occurrence it would rename the one from March 2nd, etc...

How would I go about doing this?

share|improve this question
1  
as an alternate solution, how about naming your files with a timestamp (YYYYMMDDHHMMSS -- 20120308135254). This avoids a potential bit of nasty if someone accidentally opens and writes a file in the processing queue (even if they make no changes the mtime will change, and the file will get processed out of order. If the name is the timestamp you just grab the first file you see every time and you're OK.) –  voretaq7 Mar 8 '12 at 20:05
add comment

1 Answer

mv `ls -ct file* | tail -n 1` input.dat 

will rename the oldes file that matches the pattern file* to the name input.dat.

share|improve this answer
    
simple and elegant. –  voretaq7 Mar 8 '12 at 20:01
    
note re: my comment on the question, passing -c to ls as in SvenW's answer avoids this -- it uses the create time rather than the last modify time. (I'm pretty sure AIX uses -c, as does Linux. FreeBSD (and I believe Net/OpenBSD) uses -U) –  voretaq7 Mar 8 '12 at 21:00
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.