Shell编程:从命令输出中选择随机行 [英] Shell programming: Select random line from command output

查看:94
本文介绍了Shell编程:从命令输出中选择随机行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个简单的Shell脚本,该脚本涉及从当前工作目录中选择一个随机目录,然后导航到该目录.

I'm trying to create a simple Shell script which involves selecting a random directory from the current working directory, and navigating to it.

谁能说明如何列出所有目录,然后从该列表中随机选择一个?

我试图避免将所有目录都列出到一个文本文件中,而只是从该文件中选择一条随机行(这很简单).

I'm trying to avoid listing all directories to a text file and simply selecting a random line from that file (which is simple enough).

我的最初尝试包括使用 ls -d */命令仅列出目录.此命令在输入到终端时有效,但是返回错误:

My initial attempts included using the ls -d */ command to list only directories. This command worked when it was entered into the terminal, however returned the error:

ls: */: No such file or directory

当我尝试将其实现到此脚本中时:

when I tried to implement it into this script:

DIR_LIST=` ls -d */`

echo "$DIR_LIST"

推荐答案

查找.-maxdepth 1型d!-小路 .|shuf -n 1

没有 shuf 版本:

# To exclude hidden directories, use -name like so:
# find ... -name ".*"

# A version of find using only POSIX options:
# This might be slower for large directories (untested). Will need to be modified to list anything other than current directory.
# dirs="$(find . -type d ! -path "./*/*" ! -name ".")"

# Includes hidden directories.
dirs="$(find . -maxdepth 1 -type d ! -path .)"

numlines="$(printf "%s\n" "${dirs}" | wc -l)"
lineno="$((${RANDOM} % ${numlines} + 1))"
random_line="$(printf "%s\n" "${dirs}" | sed -n "${lineno}{p;q}")"

echo "Your selected directory: ${random_line}"

编辑:基于注释的改进代码.

Improved code based on comments.

这篇关于Shell编程:从命令输出中选择随机行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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