Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort files by name using a shell script

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.

like image 948
kantawit Avatar asked Dec 22 '12 09:12

kantawit


2 Answers

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.

like image 63
ckhan Avatar answered Sep 30 '22 19:09

ckhan


(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
like image 25
Andreas Florath Avatar answered Sep 30 '22 18:09

Andreas Florath