【问题标题】:Looping through a random set of files [closed]循环遍历一组随机文件[关闭]
【发布时间】:2021-09-04 07:16:51
【问题描述】:

我有一组随机的文件要循环访问(例如,我可以复制或移动)。我正在使用命令 shuf 使用 bash 函数。

inclnm 通常包含特定文件的通配符,例如

( -name A\* -o -name B\*.mse ).

这是我想循环的随机列表命令。

shuf -n $nf < <( find $dpath -maxdepth 1 -type f "${inclnm[@]}" )

【问题讨论】:

  • 问题出在哪里?
  • shuf 的输出通过管道传送到while read filename 循环
  • 或通过管道将其传递给xargs 以将它们全部作为参数传递给另一个命令。
  • 想到了for fl in $( shuf ... ); do。但可能有更明智的方法。使用 for 循环,find 必须运行完成,并且我可以超出命令行参数。
  • 管道到while read 是最好的,以防文件名包含空格。仅当文件名包含换行符时才会失败。

标签: bash loops


【解决方案1】:

最不受欢迎的选择是使用空分隔记录:

#!/usr/bin/env bash

dpath=./
nf=10
inclnm=( -name a\* -o -name b\* )

mapfile -d '' random_files < <(
  find "$dpath" -maxdepth 1 -type f "${inclnm[@]}" -print0 |
  shuf -z -n "$nf"
)

# Debug
declare -p random_files

或者将find替换为printf

inclnm=( a* b* )

cd "$dpath" || :
mapfile -d '' random_files < <( printf %s\\0 "${inclnm[@]}" | shuf -z -n "$nf" )

或者更好的是,让shuf 直接处理参数,而不需要printffind

mapfile -d '' random_files < <( shuf -z -n "$nf" -e "${inclnm[@]}" )

请注意,最后一种方法将受到最大参数长度限制。

【讨论】:

    猜你喜欢
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 2014-06-14
    • 2016-01-31
    • 1970-01-01
    • 2014-07-15
    • 2021-12-09
    • 1970-01-01
    相关资源
    最近更新 更多