-2

How sort the below filename in order using shell script?

abcd_exp_4_20180706.txt
abcd_exp_3_20180706.txt
abcd_exp_1_20180706.txt
abcd_exp_2_20180706.txt
abcd_exp_5_20180706.txt
abcd_exp_1_20180707.txt
abcd_exp_5_20180707.txt
abcd_exp_4_20180707.txt
abcd_exp_3_20180707.txt
abcd_exp_2_20180707.txt

expected output

abcd_exp_1_20180706.txt
abcd_exp_2_20180706.txt
abcd_exp_3_20180706.txt
abcd_exp_4_20180706.txt
abcd_exp_5_20180706.txt
abcd_exp_1_20180707.txt
abcd_exp_2_20180707.txt
abcd_exp_3_20180707.txt
abcd_exp_4_20180707.txt
abcd_exp_5_20180707.txt
Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
  • 1
    Are the filenames stored in a text file? What are you wanting to do with them apart from sorting them? What is the bigger issue that you are trying to solve? – Kusalananda Jul 15 '18 at 07:03
  • @Kusalananda, No the filenames are not in text file. The files come from one of our upstream to my local directory. I want to copy this files like the mentioned sequence order to another directory one by one. – L Sundar Jul 15 '18 at 07:13
  • 1
    Why is it important that you copy them in a particular order and one by one? I'm trying to understand so that I don't solve a non-existing problem. – Kusalananda Jul 15 '18 at 07:15

1 Answers1

1

Generally, parsing the output of ls is a bad idea. However, if you know all filenames follow this same format, then it's a reasonable approach.

$ ls | sort -t_ -k4 -k3,3

Explanation

  • ls |: pipe the output of ls to…
  • sort -t_ -k4 -k3: sort using _ as a delimiter, first by the 4th column (e.g. 20180706.txt), then by the 3rd column (e.g. 1).
Sparhawk
  • 19,941
  • @Sparhawk, Thanks it works. But if the file name prefixed with some additional string means how to handle this – L Sundar Jul 15 '18 at 07:21
  • 1
    You shouldn't be using ls to do anything programmatically. – slm Jul 15 '18 at 07:22
  • adding to above comment usually my filename is abcd_exp_1_20180706.txt but sometime it have prefixed with some string like xxx_abcd_exp_1_20180706.txt and xxx_2017_abcd_exp_1_20180706.txt, I want permanent solution for this. Please help me on this – L Sundar Jul 15 '18 at 07:23
  • @slm Agreed, as per my first sentence. I've added a link to clarify to the reader. – Sparhawk Jul 15 '18 at 07:26
  • @perror Yes, I just put it in to be explicit, attempting to make it simpler to understand (but perhaps had the opposite effect). – Sparhawk Jul 15 '18 at 07:27
  • @LSundar You could rename, removing the first _, sort, then rename, adding the _ back. But you really need to add all this information in the original question, including the answers to Kusalananda's question. Please be specific in the pontential filenames. – Sparhawk Jul 15 '18 at 07:28