简体   繁体   English

ls -l->按正则表达式对文件排序

[英]ls -l -> Sort files by regex

I have a directory with log-Files from different applications which are named like: 我有一个目录,其中包含来自不同应用程序的日志文件,它们的名称如下:

A_B_C.log.20180205125615.bin
A_B_C.log.20180205125616
A_B_C_20180205133700.log
A_B_C_1234_20180205133700.log
D_E_F_G.log.20180205125715.bin
D_E_F_G.log.20180205125716
D_E_F_G_20180205133800.log
D_E_F_G_1234_20180205133800.log

The names all contain a timestamp with 14 digits (year, month, day, time). 名称都包含14位数字的时间戳(年,月,日,时间)。

I would like to print all filenames by "ls -l" and order them by the timestamp in the name. 我想通过“ ls -l”打印所有文件名,并按名称中的时间戳进行排序。

The newes Files (highest number) should be printet at the end. 新文件(最高编号)应在最后打印。 If ther are multiple matches for a timestamt, these files should be sorted in alphabetical order. 如果一个时间戳有多个匹配项,则这些文件应按字母顺序排序。

How can i combine "ls -l" with regex sorting? 如何将“ ls -l”与正则表达式排序结合使用?

Perl solution: Perl解决方案:

perl -le 'print for sort { ($a =~ /\d{14}/g)[0] cmp ($b =~ /\d{14}/g)[0]
                           or $a cmp $b } glob "*log*"'

See sort for details on how to provide custom comparators in Perl. 有关如何在Perl中提供自定义比较器的详细信息,请参见sort

  • -l adds final newlines to printed lines -l将最终换行符添加到打印行
  • \\d{14} matches 14 digits \\d{14}匹配14位数字
  • matching with the /g modifier returns the matching substrings in list context, [0] selects the first of them. /g修饰符匹配将在列表上下文中返回匹配的子字符串, [0]选择它们中的第一个。

This line with gnu sed should help: 这行与gnu sed应该会帮助:

ls -1|sed -r 's/.*([0-9]{14}).*/\1 &/' f|sort -n|sed 's/^[0-9]* //' 

Ls cannot do it on its own. Ls不能自己做。 The idea is: take the timestamp out, to the head of each line as key, then sort by timestamp, finally remove the inserted timestamp. 这个想法是:取出时间戳,以每行的开头作为键,然后按时间戳排序,最后删除插入的时间戳。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM