【问题标题】:Unix - Find and Sort by part of filenameUnix - 按文件名的一部分查找和排序
【发布时间】:2018-08-17 22:17:36
【问题描述】:

我有这个:

D-T4-0.txt 
A-2.txt 
C-3-1.txt 
B-X1-3.txt 
E-2-4.txt

我希望订购如下:

D, C, A, B, E

我需要查看每个(.txt 之前)D-0, C-1, A-2, B-3, E-4 中的最后一个数字。

有可能吗?

【问题讨论】:

    标签: sorting unix terminal find


    【解决方案1】:
    for i in `awk -F- '{print $NF}' file_name |sort`;do grep -- -$i file_name;done
    
    • 在这里,我使用由 - 分隔的 awk 提取最后一个字段并进行排序
    • 并通过在前面添加 - 使用循环对已排序的行进行 grep。

    【讨论】:

    • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
    • do 后面有一个错误的分号:)
    • 用awk我可以排序,但我需要返回文件名(命令“ls”是它告诉我文件名)我该怎么做?
    • @rsa 类似于 for i in ls |awk -F- '{print $NF}'|sort;do ls |grep -- -$i ;done
    • 在我的批处理中,for 不起作用 -bash: syntax error near unexpected token `|'
    【解决方案2】:

    您可以在这样的管道中执行此操作:

    # List files
    ls |
    
    # Include the sorting key in the front as well
    sed -E 's/^(.*)([0-9]+)\.txt$/\2\t\1\2.txt/' |
    
    # Sort on the sorting key
    sort -n |
    
    # Remove the sorting key
    cut -f2-
    
    # Grab the first letter
    cut -c1
    

    输出:

    D                                                                                                           
    C
    A
    B
    E
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-13
      • 2021-09-26
      • 1970-01-01
      • 2013-10-10
      • 2016-02-14
      • 1970-01-01
      • 2010-10-27
      • 2017-08-16
      相关资源
      最近更新 更多