Get the newest file based on timestamp

2020-02-09 04:34发布

I am new to shell scripting so i need some help need how to go about with this problem.

I have a directory which contains files in the following format. The files are in a diretory called /incoming/external/data

AA_20100806.dat
AA_20100807.dat
AA_20100808.dat
AA_20100809.dat
AA_20100810.dat
AA_20100811.dat
AA_20100812.dat

As you can see the filename of the file includes a timestamp. i.e. [RANGE]_[YYYYMMDD].dat

What i need to do is find out which of these files has the newest date using the timestamp on the filename not the system timestamp and store the filename in a variable and move it to another directory and move the rest to a different directory.

标签: bash unix shell
7条回答
干净又极端
2楼-- · 2020-02-09 05:17

This should work:

newest=$(ls | sort -t _ -k 2,2 | tail -n 1)
others=($(ls | sort -t _ -k 2,2 | head -n -1))

mv "$newest" newdir
mv "${others[@]}" otherdir

It won't work if there are spaces in the filenames although you could modify the IFS variable to affect that.

查看更多
登录 后发表回答