I would like to sort all files by date with a Shell script.
For example, in /Users/KanZ/Desktop/Project/Test/
there are the files M1.h
, A2.h
and F4.h
.
Each file has a different time. How do I sort all these files from oldest to current by date and time?
Currently I have a rename script:
cd /Users/KanZ/Desktop/Project/Test/
n=1
for file in *.jpg;
do
echo $file prefix=M file_name=M$n.jpg
echo $file_name n=$(( $n+1 ))
mv $file $file_name
done
The first time I run script the JPG files will be M1.jpg
, M2.jpg
and M3.jpg
but if I add a new file named A1.jpg
to this directory and run the script again, M1.jpg
, M2.jpg
and M3.jpg
will be replaced by M4.jpg
(before running the script, this file was named A1.jpg
) because the first letter is A
and came before M
.
I would like to get M1
, M2
, M3
and M4.jpg
.
The ls
command can easily sort by last modified time:
$ ls -1t /Users/KanZ/Desktop/Project/Test
To reverse the sort, include the -r
option:
$ ls -1tr /Users/KanZ/Desktop/Project/Test
Including the 1
tells ls
to output one file per line without extra metadata (like the length, modification time, etc), which is often what you need in a shell script if you need to send the list to other commands for further processing.
(Completely new because the question changed)
Try this:
cd /Users/KanZ/Desktop/Project/Test
n=1
for f in `ls -tr *.jpg`; do
mv $f M$n.jpg
n=$(( n + 1 ))
done
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With