Support Questions

Find answers, ask questions, and share your expertise

how to sort the file name in shell script

avatar
Rising Star

How to sort the filename in shell.

My files looks like

abcd_2_20180703

abcd_4_20180703

abcd_5_20180703

abcd_1_20180703

abcd_3_20180703

abcd_6_20180703

And i expect after the sorting

abcd_1_20180703

abcd_2_20180703

abcd_3_20180703

abcd_5_20180703

..

Please help me sort the files. TIA

1 ACCEPTED SOLUTION

avatar
Super Collaborator

@Sundar Lakshmanan

Try sort with delimiter

# ls -1 | sort -t '_' -nk3

# ls -1 | sort -t '_' -nk3
abcd_1_20180703
abcd_2_20180703
abcd_3_20180703
abcd_4_20180703
abcd_5_20180703
abcd_6_20180703
abcd_1_20180704
abcd_2_20180704
abcd_3_20180704
abcd_4_20180704
abcd_5_20180704
abcd_6_20180704

#cat test.out  | sort -t '_' -nk3

View solution in original post

5 REPLIES 5

avatar
@Sundar Lakshmanan

You can simply use "sort" command.

[root@node1 ~]# cat /tmp/a.txt
abcd_2_20180703
abcd_4_20180703
abcd_5_20180703
abcd_1_20180703
abcd_3_20180703
abcd_6_20180703


[root@node1 ~]# sort /tmp/a.txt
abcd_1_20180703
abcd_2_20180703
abcd_3_20180703
abcd_4_20180703
abcd_5_20180703
abcd_6_20180703

Let me know if this helps.

avatar
Rising Star

@Sandeep Nemuri

Thanks for your reply. the above sort will give correct output if the directory have only one day files.

if the directory have 20180704 files.

it sorted output like

abcd_1_20180703

abcd_1_20180704

abcd_2_20180703

abcd_2_20180704

abcd_3_20180703

abcd_3_20180704

abcd_4_20180703

abcd_4_20180704

abcd_5_20180703

abcd_5_20180704

abcd_6_20180703

abcd_6_20180704

But i expect

abcd_1_20180703

abcd_2_20180703

abcd_3_20180703

abcd_4_20180703

abcd_5_20180703

abcd_6_20180703

abcd_1_20180704

abcd_2_20180704

abcd_3_20180704

abcd_4_20180704

abcd_5_20180704

abcd_6_20180704

Any idea?

avatar

@Sundar Lakshmanan "sort" was for the requirement this is mentioned in the question details. You can use the command which @rguruvannagari has mentioned in the above comment to sort with the date (3rd column).

avatar
Super Collaborator

@Sundar Lakshmanan

Try sort with delimiter

# ls -1 | sort -t '_' -nk3

# ls -1 | sort -t '_' -nk3
abcd_1_20180703
abcd_2_20180703
abcd_3_20180703
abcd_4_20180703
abcd_5_20180703
abcd_6_20180703
abcd_1_20180704
abcd_2_20180704
abcd_3_20180704
abcd_4_20180704
abcd_5_20180704
abcd_6_20180704

#cat test.out  | sort -t '_' -nk3

avatar
Rising Star

Thanks @ Sandeep Nemuri @ rguruvannagari works fine