【问题标题】:Using ls -t with file names in another dir将 ls -t 与另一个目录中的文件名一起使用
【发布时间】:2015-02-12 08:44:05
【问题描述】:

我试图列出不同目录中的特定文件,而不是当前目录。

看看这个简单的日志:

[johni /share/ex_data/ex4] > ls
example.c   header1.h  header3.h
example2.c  header2.h
[johni /share/ex_data/ex4] > ls -t header*
header1.h  header2.h  header3.h
[johni /share/ex_data/ex4] > cd
[johni ~] > 
[johni ~] > 
[johni ~] > ls -t header* /share/ex_

ex_data/ex_sol/
[johni ~] > ls -t header* /share/ex_data/ex4 ls: 不匹配

如何在同一个 /share/ex_data/ex4 目录上使用另一个目录中的“ls”命令?

谢谢!!。

【问题讨论】:

    标签: shell directory ls


    【解决方案1】:

    ls 在另一个目录上:

    ls -t /share/ex_header*
    

    【讨论】:

    • 这与所需的输出不同,因为单个文件名包含它们的路径。这可能没问题,但话又说回来,也可能不行。
    【解决方案2】:

    如果您希望输出包含限定目录名,那么您可以简单地使用

    ls -t /share/ex_data/ex4/header*
    

    如果您不希望包含目录名称,请在调用 ls 之前使用更改目录的子 shell(作为性能增强,这使用 exec 仅生成一个新的进程表条目,而不是可能需要二):

    (cd /share/ex_data/ex4 && exec ls -t header*)
    

    也就是说,如果这是为脚本执行的——比如,查找最新或最旧的文件名——它是bad practice to parse lsother techniques 可用于查找最新或最旧的文件(如果您只想这样做,您应该点击上面的后一个链接,而不是使用下面给出的更复杂的代码来提供完整的排序)。

    例如,如果您有 GNU find、GNU sort 和 bash,并希望通过 mtime 将文件列表加载到数组中,则以下将使用文件名,这将完全抛弃 ls -t -- 包括包含换行符之类的名称:

    filenames_by_mtime=( )
    while read -r -d ' ' time && IFS= read -r -d '' filename; do
      filenames_by_mtime+=( "$filename" )
    done < <(find /share/ex_data/ex4 \
               -maxdepth 1 \
               -type f \
               -name 'header*' \
               -printf '%T@ %P\0' \
             | sort -z -n)
    

    ...然后可以使用"${filenames_by_mtime[@]}" 扩展此数组,或为单个条目编制索引——例如,最旧的文件将是"${filenames_by_mtime[0]}"

    【讨论】:

      猜你喜欢
      • 2021-03-22
      • 1970-01-01
      • 2016-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多