问题描述
我正在编写一个 bash 脚本,其中一项需要执行的任务是通过 curl 连接到 FTP 服务器并找到最后修改的 .zip 文件的名称.
I'm writing a bash script and one of the tasks which needs performing is to connect to an FTP server via curl and find the name of the last modified .zip file.
我们正在查看的文件的名称格式是MM_DD_YYYY_ALL.zip
.
The name format of the files we are looking at is MM_DD_YYYY_ALL.zip
.
到目前为止,我有,<<>>
:
export FILEPATTERN=_ALL.zip
for FILE in `curl -u << SERVER INFO >> 2> /dev/null | grep ${FILEPATTERN} | awk -F '{print $9}'`
do
...
# Do stuff with each file to determine most recent version.
...
done
文件名未格式化的事实 YYYY_MM_DD
似乎是无法通过一些快速修剪和计算来完成的主要原因.
The fact that the file name isn't formatted YYYY_MM_DD
seems to be the main reason this can't be done with some quick trimming and calculations.
是否有一种有效的方法可以从此列表中提取最新修改的 zip 文件的名称?或者在生成列表时是否可以进行一些处理?
Is there an efficient way to pull the name of the most recent modified zip file from this list? Or is there some processing which can be done whilst the list is being generated?
干杯.
推荐答案
您可以使用多键 sort
命令一次性对文件名进行排序,并使用 tail 获取最新文件.
You can sort the filenames in one shot with a multi-key sort
command and grab the last line with tail
to get the latest file.
您需要指定 -t-
使用破折号作为排序的字段分隔符,-n
获得数字排序,并按顺序列出每个字段其优先事项.字段说明符的格式为:
You'll need to specify -t-
to use a dash as sort's field separator, -n
to get a numeric sort, and list each field in the order of its priority. The format for a field specifier is:
-k, --key=POS1[,POS2] start a key at POS1 (origin 1), end it at POS2
(default end of line)
因此,对于年份,字段 3,您需要将其以 4 个字符的宽度列为 -k3,4
.
So for the year, field 3, you'll need to list it with its 4-character width as -k3,4
.
如果您按照年、月和日的顺序对字段进行排序,您最终会得到一个列表,其中包含按日期顺序排列的所有文件.
If you sort by the year, month, and day fields in that order, you'll end up with a list that has all the files in date order.
所以代替上面的 for
循环,你可以使用:
So instead of the for
loop above, you can use:
FILE=`curl -u << SERVER INFO >> 2> /dev/null | grep ${FILEPATTERN} | awk -F '{print $9}'
| sort -n -t- -k3,4 -k1,2 -k2,2 |tail -1`
这篇关于使用带有 curl 的 bash 脚本通过 FTP 检索目录中最后修改的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!