Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Based from this question, The HTML files date format has been changed. All of the HTML files have the date such like below:


dateishere is intentionally added by me in the files, so I can easily pinpoint those date location.

And now, in the directory of the HTML files, I want to move one file at a time based on that date.

If move one file at a time without care about which file moved first, I can simply use

for file in $(ls | tail -1);
mv $file /other/location

But how to move the oldest file first based on the date in XXXXXXXXdateishere? (this means, HTML file contains 20100110dateishere moved first before 20100111dateishere, and then next file; based on the date)

(note: 20100111 means 11 January 2010)

share|improve this question
up vote 3 down vote accepted

This should do it:

for i in $(grep dateishere *.html | sed 's/\(.*\):.* \([0-9]*dateishere\).*/\1 \2/' | sort -k 2 | awk '{print $1}')
  mv $i blarg/
share|improve this answer
for dateNfile in $(grep dateishere *html | sed -r 's/^([^:]*):(.*)dateishere/\2:\1/' | sort -n)
  # echo date=${dateNfile/:*/}
  mv $name /other/location

So I guess there is just one line per file, containing 'dateishere', and that the line starts with the date, but the sed command could be modified, to cut the date even in other cases.

If you have blanks in the filenames, or linebreaks and such, things get a bit more complicated, so I would like to ignore these, if possible. But from your assertion, this isn't the case.

share|improve this answer
Where does the mv come in? – Caleb Jul 30 '11 at 20:15
And now, Ladies and Gentlemen, the mv comes in! (I thought it was obvious). – user unknown Jul 30 '11 at 20:42

Your Answer


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.