如何从 Bash 脚本中的 <string>_# 文件名系列中选择最高数字 [英] How do I Select Highest Number From Series of <string>_# File Names in Bash Script

查看:54
本文介绍了如何从 Bash 脚本中的 <string>_# 文件名系列中选择最高数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含文件的目录

I have a directory with files

heat1.conf
heat2.conf
...
heat<n>.conf
minimize.conf
...
other files....

我希望我的 Bash 脚本能够获取最高编号的文件名(这样我可以在发现错误情况时删除并替换它).

I want my Bash script to be able to grab the highest number filename (so I can delete and replace it when I find an error condition).

实现这一目标的最佳方法是什么?

What's the best way to accomplish this?

请讨论您的解决方案的速度以及您认为这是最佳方法的原因.

Please discuss the speed of your solution and why you think that it is the best approach.

推荐答案

如果您打算只在当前目录中列出您的文件,那么就不需要使用 find 和 maxdepth 1 或使用 ls.只需使用带有外壳扩展的 for 循环即可.此外,expr 是外部的.如果您的数字不包含小数,您可以只使用 bash 自己的比较.

If you are going to list your file only in current directory, then there's no need to use find with maxdepth 1 or use ls. Just use a for loop with shell expansion. Also, expr is external. if your number doesn't contain decimals, you can use just bash's own comparison.

max=-1
for file in heat*.conf
do
  num=${file:4}
  num=${file%.conf}
  [[ $num -gt $max ]] && max=$num    
done
echo "max is: $max"

这篇关于如何从 Bash 脚本中的 &amp;lt;string&amp;gt;_# 文件名系列中选择最高数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆