linux - 从 args 中选择随机条目的更好方法?

标签 linux bash

只是想知道,因为我上个月突然想到了这个。

#!/usr/bin/bash

# Collects all of the args, make sure to seperate with ','
IN="$*"

# Takes everything before a ',' and places them each on a single line of tmp file
echo $IN | sed 's/,/\n/g' > /tmp/pick.a.random.word.or.phrase

# Obvious vars are obvious
WORDFILE="/tmp/pick.a.random.word.or.phrase"

# Pick only one of the vars
NUMWORDS=1

## Picks a random line from tmp file

#Number of lines in $WORDFILE
tL=`awk 'NF!=0 {++c} END {print c}' $WORDFILE`

# Expand random
RANDOM_CMD='od -vAn -N4 -tu4 /dev/urandom'

for i in `seq $NUMWORDS`
do
rnum=$((`${RANDOM_CMD}`%$tL+1))
sed -n "$rnum p" $WORDFILE | tr '\n' ' '

done

printf "\n"

rm /tmp/pick.a.random.word.or.phrase

主要是问:

  1. 我需要一个 tmp 文件吗?
  2. 有没有办法在一行中与另一个程序一起执行此操作?
  3. 如何尽可能浓缩?

最佳答案

在我看来,命令行参数处理很奇怪。为什么不直接使用普通的命令行参数呢?这使问题变得微不足道:

#!/usr/bin/bash
shuf -en1 "$@"

当然,你也可以只用shuf -en1,也就是九次击键:

$ shuf -en1 word another_word "random phrase"
another_word
$ shuf -en1 word another_word "random phrase"
word
$ shuf -en1 word another_word "random phrase"
another_word
$ shuf -en1 word another_word "random phrase"
random phrase

shuf 命令行标志:

-e    Shuffle command line arguments instead of lines in a file/stdin
-n1   Produce only the first random line (or argument in this case)

如果你真的坚持把参数放在一起然后用逗号分隔它们,你可以使用下面的。与您的原件一样,如果参数中的某些单词可以全局扩展,它将表现出意想不到的行为,所以我真的不推荐它:

#!/usr/bin/bash
IFS=, read -ra args <<<"$*"
echo $(shuf -en1 "${args[@]}")

第一行组合参数,然后将结果以逗号分割成数组args。 (要读取的 -a 选项。)由于字符串以逗号分隔,因此保留空格(例如通过参数连接自动插入);为了删除空格,我通过不引用命令扩展来拆分 shuf 的结果。

关于linux - 从 args 中选择随机条目的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39050446/

相关文章:

linux - Shell 脚本 - 两个 for 循环和更改文件扩展名

linux - 预定的 cron 作业不工作

c - Linux RCU 和双向链表

bash - -bash : ant: command not found on mac os x El Capitan

linux - 在bash中为postgresql生成随 secret 码

linux - 是否可以在BASH环境中创建和操作对象列表

linux - 从用户空间启用/读取 PMU

linux - 如何使用 WGET 仅获取状态信息并将其保存在某处?

linux - 如果 BASH 则不止一个

bash - 从 bash 脚本发送kill -s USR1 会停止进程,而从终端执行相同操作不会停止进程