0

I have a series of 300+ files that I need to sort twice, once by the date and a second time within that date by part of the filename.
The only standard in the names is that ends with *mmddyyyy<time stamp>.csv, where the first part of the file name can include anything at all. I know ls -ltr gives me the date sort but I can't seem to capture and sort on a portion of the last keydef.

  • They even have spaces in the file names... :( – Maria Olivero Jan 19 '16 at 16:46
  • 2
    Although names can vary, can you still post three full file names, so don't do <time stamp> do the actual time stamp for example. That way it makes it possible to see if there is some pattern that can be usable for sorting. – clarity123 Jan 19 '16 at 16:52
  • 2
    Maybe a sample input and expected output could help clarify what you want to do. – Stéphane Chazelas Jan 19 '16 at 17:05
  • These guys were real buggers... the front part of the filename is literally anything at all - whatever a human typed in. Some of the problem children were names like - "180195-49 (2).hdl.02042015021509.csv" or "15-1 15-2.hdl.03302015064508.csv" but more "normalized" names were "2-17-15.hdl.02172015085537.csv" as examples. – Maria Olivero Jan 21 '16 at 4:15
0

Given that when looking at the filenames from the end side they have a predictable format (extension then time then date) one can leverage this fact and use the following command:

ls -1 | rev | sort -t '~' -k1.14,1.14 -k1.13,1.13 -k1.12,1.12 -k1.11,1.11 -k1.18,1.18 -k1.17,1.17 -k1.16,1.16 -k1.15,1.15 | rev

Explanation:
- the filenames are first reversed so we can access the desired format
- the result is then sorted character by character, depending on our needs:
- - the characters 11 to 14 are the year (in reverse order)
- - the characters 17 to 18 are the month (in reverse order)
- - the characters 15 to 16 are the day (in reverse order)
- finally another reversal takes place to display them with original names

I've used the tilde ~ as separator in order to combine the whole filename in one field but you can play around using a different one (it has to be a character never present in the filenames) or just use a . (dot) in order to split the filename in several fields (if their amount is always the same) so that you can specify other parts to be sorted upon - for your second question.

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.