gpt4 book ai didi

linux - 如何在 bash 中使用 $find 命令抑制文件夹排序

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:54:35 24 4
gpt4 key购买 nike

我有一个文件夹,其中包含 ID 为 Guid 的项目。我的脚本迭代这个文件夹来提交子进程。我发现用于将文件夹内容检索到集合中的 find 命令正在按排序顺序检索它们。我需要这个按照先进先出的顺序。我希望它们按照放置在文件夹中的顺序排列(这是一个伪“队列”;内容是要提交给流程的作业)。

这是我的 find 命令。我能做什么?

DIRECTORIES=$(find $queue_root -mindepth 1 -type d)

最佳答案

您可以按以下方式对 find 返回的列表进行排序:

#!/usr/bin/env bash

queue_root=.

# print the list of directories preceded by their timestamp
find "$queue_root" -mindepth 1 -type d -printf '%A@ %f\n' |
# sort the list by timestamps
sort -n |
# print only the directory names from the sorted list
awk '{ print $2 }'

要处理带有任意字符的目录名称,如换行符或其他不可打印的字符,可以像这样修改上面的脚本:

#!/usr/bin/env bash

queue_root=.

# Handling directories with arbitrary characters

while IFS= read -r -d '' directory; do
echo "$directory" # do stuff with directory
done < <(
# print the null delimited list of directories preceded by their timestamp
find "$queue_root" -mindepth 1 -type d -printf '%A@ %f\0' |
# sort the list by timestamps
sort --numeric-sort --zero-terminated |
# print only the directory names from the sorted list
cut --delimiter=' ' --fields=2- --zero-terminated
)

使用 POSIX 受限 shell,您可以使用 xargs 来分发目录,如下所示:

#!/usr/bin/env sh

queue_root=.
# Handling directories with arbitrary characters

# print the null delimited list of directory preceded by their timestamp
find "$queue_root" -mindepth 1 -type d -printf '%A@ %f\0' |
# sort the list by timestamps
sort --numeric-sort --zero-terminated |
# print only the directory names from the sorted list
cut --delimiter=' ' --fields=2- --zero-terminated |
# use xargs to provide the directory argument to command
# from the null delimited list of directories
xargs --null --max-args=1 echo # replace echo with command to do stuff with directory

关于linux - 如何在 bash 中使用 $find 命令抑制文件夹排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57578614/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com