【问题标题】:Shell script to find files after certain modified date and sort them in order of modified dateShell脚本在某个修改日期之后查找文件并按修改日期的顺序对它们进行排序
【发布时间】:2018-04-17 16:52:32
【问题描述】:

我正在尝试使用 shell 脚本按照修改日期的排序顺序从目录中查找某个修改日期之后的所有文件。这是我当前的 shell 脚本的一部分。

条件包含两个步骤:1)在某个修改日期之后从目录中获取文件。 2) 按修改日期对文件进行排序。

当前目录包含如下文件:

Mar 28 11:14 file_H_1
Apr  2 16:37 file_K_2
Apr  1 21:43 file_H_3
Apr 16 19:16 file_H_4
Apr 16 21:00 file_H_5
Apr 16 12:00 file_L_6
Apr  9 14:08 file_B_7
Apr  4 00:39 file_H_8
Apr  4 00:39 file_H_9
Apr  4 00:39 file_C_10
Apr  4 00:39 file_H_11
Mar 27 14:39 file_H_12

我希望最终输出为“2018-04-09 00:00:00”之后修改日期的文件列表,并按修改日期排序。 输出应该是:

file_B_7
file_L_6
file_H_4
file_H_5

我试过这个:
1) 用于在某个修改日期之后获取文件

find . -type f -newermt "2018-04-09 00:00:00"
OUTPUT of this:
file_L_6
file_H_5
file_B_7
file_H_4

2) 在修改日期对文件进行排序

ls -lt
OUTPUT of this
Apr 16 21:00 file_H_5
Apr 16 19:16 file_H_4
Apr 16 12:00 file_L_6
Apr  9 14:08 file_B_7
Apr  4 00:39 file_H_8
Apr  4 00:39 file_H_9
Apr  4 00:39 file_C_10
Apr  4 00:39 file_H_11
Apr  2 16:37 file_K_2
Apr  1 21:43 file_H_3
Mar 28 11:14 file_H_1
Mar 27 14:39 file_H_12

但我正在努力将这两个条件结合起来。

我也试过了,但它是在文件名上排序,而不是在修改日期:

find . -type f -newermt "2018-04-9 00:00:00" | sort -n | while read file_name; do
echo file=$file_name
done
    OUTPUT of this:
    file_B_7
    file_H_4
    file_H_5
    file_L_6

请提出一些解决方案。

【问题讨论】:

    标签: linux bash shell unix


    【解决方案1】:

    findls -t 与管道结合使用:

    find -type f -newermt "2018-04-09 00:00:00" | xargs ls -tl
    

    xargsfind 的输出提供给ls

    如果您的某些文件名有空格,请使用:

    find -type f -newermt "2018-04-09 00:00:00" -print0 | xargs -0 ls -tl
    

    -print0 选项允许使用文件名分隔符作为\0xargs 需要带有选项 -0 的分隔符。

    请注意,如果您想要相反的时间顺序,可以使用ls -ltr

    无论如何,您都不应该解析ls (Ref) 的结果。

    【讨论】:

    • 在两者之间添加 awk '{print "\""$0"\""}' 以处理带有空格的文件名。
    • @Kokogino 我不会那样做,而是使用print0
    【解决方案2】:

    除了使用xargs ls,您还可以将查找输出直接插入ls 命令行:

    ls -tr `find -type f -newermt "2018-04-09 00:00:00"`
    

    请注意,如果不是所有文件名都适合一个命令行,这两种方法都会失败 - xargs ls 没有正确排序,这里会出现错误消息。

    【讨论】:

      【解决方案3】:

      试试这个..

      ls -t | find . -type f -newermt "2018-04-09 00:00:00"

      【讨论】:

        【解决方案4】:

        这应该可以解决问题。

        ls -t | egrep "$(find * -maxdepth 0 -type f -newermt "2018-04-9 00:00:00" -print | sed 's/|/\\|/g' | tr '\n' '|' | sed 's/|$//')"
        

        【讨论】:

          猜你喜欢
          • 2016-04-01
          • 2011-09-15
          • 1970-01-01
          • 2012-08-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-02
          相关资源
          最近更新 更多