Issue
I have group of files in a folder in following pattern file_20230502181430
i.e.
file_$(date +"%Y%m%d%H%M%S")
What I want is to read all these files in an array to sort them by the date at the end i.e. _$(date +"%Y%m%d%H%M%S")
, to keep the most recent 3 files and delete rest.
How can I sort an output of ls file_*
according to dates at the end of file name and have them in an array to achieve what I want? If doing it with ls
isn't possible, is there another or better way to do it?
Solution
With bash
. I assume that the current directory contains the files mentioned.
# expand file_* with globbing to an array
names=( file_* )
# delete all files except the last (newest) three.
for (( index=0; index<${#names[@]}-3; index++ )); do
echo rm "${names[$index]}";
done
If output looks okay, remove echo
.
Answered By - Cyrus Answer Checked By - Willingham (WPSolving Volunteer)