How do I move the oldest or newest file in a direc

2020-04-30 20:47发布

I'm trying to us the following command on Mac OSX 10.6 Terminal but it does not work..Any idea what I may be doing wrong?

These work...

List most recent file:

ls -l -t | head -2

List oldest file:

$ ls -gt | tail -1

But when I try to Move the oldest file, with this it doesn't work:

mv `ls -tr |tail -1` newdirname

Any ideas or tips are appreciated!! And please be gentle guys, I'm not so good at this command line stuff yet ; )

Thanks,

Jess

Ps.

When I enter this:

mv `ls -tr |tail -1` DropBox

I get this: mv: rename Test.txt to DropBox/Test.txt: No such file or directory

4条回答
叛逆
2楼-- · 2020-04-30 20:56

Assuming the files you are moving are in the current directory:

mv "`ls -1t | tail -1`" dir_to_move_to

the quote help for spaces in filename, but I don't think my answer is elegant, any more elegant solution?

查看更多
仙女界的扛把子
3楼-- · 2020-04-30 20:59

Adding the parameter -1 to your ls will fix that. Seems like osx' ls doesn't check correctly whether it prints to a terminal or a pipe..

查看更多
Melony?
4楼-- · 2020-04-30 21:07

I found the another answer for the problem. The best to use find command instead of using ls command. It would help to find the oldest file and can use mv command to move to another directory.

mv $(find /home/balaji/work/ -type f -printf '%T+ %p\n' | sort | head -1) /home/balaji/regular_archieve

find – Search for files in a directory hierarchy. /home/balaji/work/ – Search location. /home/balaji/regular_archieve/ – Target location. type -f – Searches only the regular files. -printf ‘%T+ %p\n’ – Prints the file’s last modification date and time in separated by + symbol. (Eg. 2015-07-22+13:42:40.0000000000). Here, %p indicates the file name. \n indicates new line. sort | head -n 1 – The sort command sorts the output and sends the output to head command to display the oldest file. Here, -n 1 indicates only one file i.e oldest file.

查看更多
干净又极端
5楼-- · 2020-04-30 21:21

You're moving the newest file. Try

mv `ls -t |tail -1` newdirname

or

mv `ls -tr |head -1` newdirname

Working on my Ubuntu's bash.

查看更多
登录 后发表回答