Issue
I have a directory that contains files ending in a timestamp. I would like to iterate through the files in this directory order by that timestamp in the name. I am doing this in a shell script in Unix.
filename1_20230517_065806.txt
filename2_20230517_055806.txt
filename_3_20230517_125806.txt
file_name_4_20230517_063806.txt
I need this to be processed in the following order
filename2_20230517_055806.txt
file_name_4_20230517_063806.txt
filename1_20230517_065806.txt
filename_3_20230517_125806.txt
The order should only be looking at the time section of the file name. I was hoping to do something like this, but since the filed names can have any number of underscores I'm having difficulties.
for i in $(ls *.txt | sort -t'_' -k3)
do...
Is there a way to have sort look at the last delimited index and sort by that?
Solution
You can use "rev" to reverse the elements and than sort with the first two elements:
#!/bin/bash
filenames="filename1_20230517_065806.txt filename2_20230517_055806.txt filename_3_20230517_125806.txt file_name_4_20230517_063806.txt"
# Convert the filenames string into an array
IFS=' ' read -r -a files_array <<< "$filenames"
# Sort the array based on the timestamp with reversed elements
sorted_array=($(for file in "${files_array[@]}"; do
timestamp=$(echo "$file" | rev | cut -d_ -f1,2 | rev)
echo "$timestamp $file"
done | sort | cut -d' ' -f2))
for file in "${sorted_array[@]}"; do
echo "$file"
done
The output looks like expected:
filename2_20230517_055806.txt
file_name_4_20230517_063806.txt
filename1_20230517_065806.txt
filename_3_20230517_125806.txt
Answered By - DTNGNR Answer Checked By - Mary Flores (WPSolving Volunteer)