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)


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/
| 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.

| 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 clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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