7

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.

4

4 回答 4

10

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.

于 2012-12-22T09:52:26.540 回答
3

(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
于 2012-12-22T09:53:33.813 回答
0

如果您需要按升序对文件路径进行排序

ls -tUr -d $PWD/* 

可能有用

于 2014-03-09T16:51:43.810 回答
0

您需要将-t选项传递给ls命令。该-t选项按修改时间排序,即在按字典顺序对操作数进行排序之前最先修改的时间。换句话说,可以使用以下命令显示上次下载的文件。

打开终端并键入以下命令。

ls -t
于 2016-11-02T16:47:05.433 回答