如何从SFTP生成的文件列表中识别最新XLS文件
解决SFTP导出文件列表中识别最新XLS文件的问题
Got it, let's tackle this problem step by step. You've already exported the .xls file list from SFTP into list.txt using that batch command—now we just need to parse that output to find the newest file. I'll share two approaches depending on your SFTP server's capabilities:
方法1:如果SFTP支持按时间排序(更高效)
First, check if your SFTP server allows the ls -lt command (which sorts files by modification time, newest first). If it works, you can skip generating list.txt entirely and get the newest file directly:
sftp -b - hostname <<EOF ls -lt *.xls EOF | awk 'NR>1 {print substr($0, index($0,$9))}' | head -n1
解释:
ls -lt *.xls让SFTP按修改时间倒序列出XLS文件(最新的排在最前面)awk 'NR>1 ...'跳过第一行(通常是显示总大小的total <size>行),并提取完整文件名(用substr从第9列开始截取,支持文件名带空格的情况)head -n1取第一行结果,就是你要的最新文件
方法2:处理已生成的list.txt文件
如果你的SFTP服务器不支持ls -lt,我们可以用shell工具解析已有的list.txt。核心思路是把人类可读的日期格式转换成可排序的字符串,再通过排序找到最新条目。
用这个命令:
awk '{ # 把月份缩写映射成两位数字 split("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec", months, " "); for(i=1; i<=12; i++) month_map[months[i]]=sprintf("%02d", i); # 处理日期格式:当年的显示时间,往年的显示年份 if($8 ~ /:/) { current_year=strftime("%Y"); sortable_date=current_year "-" month_map[$6] "-" $7 " " $8; } else { sortable_date=$8 "-" month_map[$6] "-" $7 " 00:00"; } # 提取完整文件名(支持带空格的情况) full_name=substr($0, index($0,$9)); print sortable_date " " full_name }' list.txt | sort -r | head -n1 | awk '{print substr($0, index($0,$3))}'
解释:
- 月份映射:把
Mar这类缩写转换成03,让日期可以按数字排序 - 日期处理:区分带时间的条目(当年文件)和带年份的条目(往年文件),生成标准的
YYYY-MM-DD HH:MM格式字符串 - 文件名提取:截取完整文件名,兼容带空格的情况
- 排序取值:按时间倒序排序,取第一行就是最新文件
内容的提问来源于stack exchange,提问作者user2058738




