Jas*_*ith 46 random bash shell file
从shell脚本中的目录中选择随机文件的最佳方法是什么?
这是我在Bash中的解决方案,但我会对在Unix上使用的更便携(非GNU)版本非常感兴趣.
dir='some/directory'
file=`/bin/ls -1 "$dir" | sort --random-sort | head -1`
path=`readlink --canonicalize "$dir/$file"` # Converts to full path
echo "The randomly-selected file is: $path"
Run Code Online (Sandbox Code Playgroud)
有人还有其他想法吗?
编辑: lhunath对解析提出了一个很好的观点ls.我想这取决于你是否想要携带.如果您有GNU findutils和coreutils,那么您可以:
find "$dir" -maxdepth 1 -mindepth 1 -type f -print0 \
| sort --zero-terminated --random-sort \
| sed 's/\d000.*//g/'
Run Code Online (Sandbox Code Playgroud)
哇,这很有趣!此外,它更符合我的问题,因为我说"随机文件".但是很幸运的是,现在很难想象在安装了GNU而不是Perl 5的情况下部署的Unix系统.
lhu*_*ath 59
files=(/my/dir/*)
printf "%s\n" "${files[RANDOM % ${#files[@]}]}"
Run Code Online (Sandbox Code Playgroud)
并且不要解析ls.读http://mywiki.wooledge.org/ParsingLs
编辑:祝你找到一个bash可靠的非解决方案.对于某些类型的文件名,大多数都会中断,例如带有空格或换行符或破折号的文件名(纯粹几乎不可能sh).为了做到这一点bash,你需要完全迁移到awk/ perl/ python/ ...而无需管道输出以进行进一步处理等.
joh*_*nyB 31
"shuf"不便携吗?
shuf -n1 -e /path/to/files/*
Run Code Online (Sandbox Code Playgroud)
或者查找文件是否比一个目录更深:
find /path/to/files/ -type f | shuf -n1
Run Code Online (Sandbox Code Playgroud)
它是coreutils的一部分,但你需要6.4或更新才能得到它...所以RH/CentOS不包含它.
就像是:
let x="$RANDOM % ${#file}"
echo "The randomly-selected file is ${path[$x]}"
Run Code Online (Sandbox Code Playgroud)
$RANDOM在 bash 中是一个返回随机数的特殊变量,然后我使用模除法来获取有效索引,然后在数组中引用该索引。