选择从目录中的shell脚本一个随机文件的最佳方法 [英] Best way to choose a random file from a directory in a shell script

查看:1613
本文介绍了选择从目录中的shell脚本一个随机文件的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是选择从目录中一个随机文件在shell脚本的最佳方式?

下面是我在巴什解决方案,但我将是一个更便携(非GNU)版本使用在Unix上正确的。

非常感兴趣

  DIR ='一些/目录
文件=`/斌/ LS -1$目录|排序--random排序|头-1`
路径=`的readlink --canonicalize$ DIR / $文件`#转换为完整路径
回声随机选择的文件是:$ PATH

任何人有任何其他的想法?

编辑: lhunath使有关分析 LS好点。我猜它归结到你是否想成为便携与否。如果你有GNU的findutils和coreutils的,那么你可以这样做:

 找到$目录-maxdepth 1 -mindepth 1型的F -print0 \\
  |排序--zero终止--random排序\\
  | SED的/ \\ D000 * //克/'

哇,这很有趣!此外,它匹配的,因为我说:随机文件我的问题更好。 Honsetly虽然,这些天很难想象部署在那里有安装GNU但不使用Perl 5 Unix系统。


解决方案

 文件=(/我的/ DIR / *)
printf的%S \\ n$ {文件[RANDOM%$ {#文件[@]}]}

不解析LS 。阅读 http://mywiki.wooledge.org/ParsingLs

编辑:祝你好运找到一个非 - 庆典解决方案,这是可靠的。大多数将打破某些类型的文件名,如空格或换行或破折号文件名(这是pretty纯太多不可能 SH )。这样做的权利,而不庆典,你需要完全迁移到 AWK / 的perl / 蟒蛇 / ...不包括管道的输出,用于进一步加工或等。

What is the best way to choose a random file from a directory in a shell script?

Here is my solution in Bash but I would be very interested for a more portable (non-GNU) version for use on Unix proper.

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"

Anybody have any other ideas?

Edit: lhunath makes a good point about parsing ls. I guess it comes down to whether you want to be portable or not. If you have the GNU findutils and coreutils then you can do:

find "$dir" -maxdepth 1 -mindepth 1 -type f -print0 \
  | sort --zero-terminated --random-sort \
  | sed 's/\d000.*//g/'

Whew, that was fun! Also it matches my question better since I said "random file". Honsetly though, these days it's hard to imagine a Unix system deployed out there having GNU installed but not Perl 5.

解决方案

files=(/my/dir/*)
printf "%s\n" "${files[RANDOM % ${#files[@]}]}"

And don't parse ls. Read http://mywiki.wooledge.org/ParsingLs

Edit: Good luck finding a non-bash solution that's reliable. Most will break for certain types of filenames, such as filenames with spaces or newlines or dashes (it's pretty much impossible in pure sh). To do it right without bash, you'd need to fully migrate to awk/perl/python/... without piping that output for further processing or such.

这篇关于选择从目录中的shell脚本一个随机文件的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆