Sort ls命令的输出根据文件名中的日期。

huangapple go评论43阅读模式
英文:

Sort output of ls as per the date in the filenames

问题

我想要读取文件夹中按以下模式命名的一组文件 file_20230502181430,即

file_$(date +"%Y%m%d%H%M%S")

我想要的是将所有这些文件读取到一个数组中,按文件名末尾的日期 _$(date +"%Y%m%d%H%M%S") 进行排序,保留最近的3个文件并删除其余的文件。

如何根据文件名末尾的日期对 ls file_* 的输出进行排序,并将它们存储在一个数组中,以实现我想要的目标?如果使用 ls 不可行,是否有另一种或更好的方法?

英文:

I have group of files in a folder in following pattern file_20230502181430 i.e.

file_$(date +"%Y%m%d%H%M%S")

What I want is to read all these files in an array to sort themby the date at the end i.e. _$(date +"%Y%m%d%H%M%S"), to keep the most recent 3 files and delete rest.

How can I sort an output of ls file_* according to dates at the end of file name and have them in an array to achieve what I want? If doing it with ls isnt possible, is there another or better way to do it?

答案1

得分: 2

使用 bash。我假设当前目录包含所提到的文件。

# 使用通配符扩展 file_* 到一个数组
names=( file_* )

# 删除除了最后三个(最新的)之外的所有文件。
for (( index=0; index<${#names[@]}-3; index++ )); do
  echo rm "${names[$index]}";
done

如果输出看起来正常,请移除 echo

英文:

With bash. I assume that the current directory contains the files mentioned.

# expand file_* with globbing to an array
names=( file_* )

# delete all files except the last (newest) three.
for (( index=0; index&lt;${#names[@]}-3; index++ )); do
  echo rm &quot;${names[$index]}&quot;;
done

If output looks okay, remove echo.

答案2

得分: 1

检查这个:

for file in $(ls -1 file_* | sort -t_ -k2 | head -n -3)
do
    echo "删除文件:$file"
done

更好的方法:

for file in file_*
do 
    echo "删除文件:$file"
done | sort -t_ -k2 | head -n -3
英文:

check this out :

for file in $(ls -1 file_* | sort -t_ -k2 | head -n -3)
do
     echo &quot;Deleting file: $file&quot;
done

better approach

for file in file_*
do 
     echo &quot;Deleting file: $file&quot;
done | sort -t_ -k2 | head -n -3

huangapple
  • 本文由 发表于 2023年7月3日 02:31:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76600272.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定