首页 > 解决方案 > 循环遍历一组随机文件

问题描述

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

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

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

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

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

标签: bashloops

解决方案


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

#!/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

或者替换findprintf

inclnm=( a* b* )

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

或者更好的是,让我们shuf直接处理参数而不需要printfor find

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

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


推荐阅读