How can I sort a list of directories alphabetically and get the first value that sorts after a specific string?
for dir in ????-??-??--??:??:??/; do
if [[ $dir > "2020-01-05--00:00:00" ]]; then
printf '%s\n' "$dir"
# process "$dir" here
break
fi
done
The above script will loop through the directories in the current directory whose names matches the pattern ????-??-??--??:??:??
.
For each directory, it is compared to the string 2020-01-05--00:00:00
. If it sorts after that string lexicographically, the name of the directory is printed and the loop is exited.
This works since the list resulting from a pathname expansion is sorted according to the current collating order (just like ls
sorts the list by default).
To copy that directory to elsewhere, replace the comment with something like
rsync -av "$dir" /somewhere/elsewhere
The following is a script that takes the particular string from its first command line argument and does the same thing:
#!/bin/bash
for dir in ????-??-??--??:??:??/; do
if [[ $dir > "$1" ]]; then
printf '%s\n' "$dir"
# process "$dir" here
break
fi
done
Testing this with the directories that you list:
$ ls -l
total 10
drwxr-xr-x 2 myself wheel 512 Jan 24 11:14 2019-12-04--16:12:56
drwxr-xr-x 2 myself wheel 512 Jan 24 11:14 2019-12-09--13:36:53
drwxr-xr-x 2 myself wheel 512 Jan 24 11:14 2020-01-23--13:24:13
drwxr-xr-x 2 myself wheel 512 Jan 24 11:14 2020-01-23--13:47:03
-rw-r--r-- 1 myself wheel 119 Jan 24 11:23 script.sh
$ ./script.sh "2020-01-05--00:00:00"
2020-01-23--13:24:13/
I came up with
$ printf '%s\n' ????-??-??--??:??:?? | awk '$1 > "2020-01-05--00:00:00"{print;exit}'
2020-01-23--13:24:13
With zsh
:
ref=2020-01-05--00:00:00
list=($ref *(DN/oN)) # list is ref + all directories unsorted
list=(${(o)list}) # sort the list (as per locale collation algorithm)
print -r -- ${list[$list[(ie)$ref] + 1]-none}
(where $array[(ie)string]
expands to the array i
ndex of the element that is e
xactly string
).