我写了一个简单的bash脚本,它从文件或STDIN转储一个随机行:
#!/bin/bash
if [ $# -ne 1 ]
then
echo "Syntax: $0 FILE (or \'-\' for STDIN)"
echo $0 - display a random line from FILE
exit 1
fi
RAND=`cat /proc/sys/kernel/random/uuid | cut -c1-4 | od -d | head -1 | cut -d' ' -f2`
if [ $1 != "-" ]
then
LINES=`cat "$1" | wc -l`
LINE=`expr $RAND % $LINES + 1`
head -$LINE $1 | tail -1
else
piped=`cat -`
LINES=`echo "$piped" | wc -l`
LINE=`expr $RAND % $LINES + 1`
echo "$piped" | head -$LINE | tail -1
fi
但是,如果没有传递选项,我希望它也处理STDIN(但如果管道中没有STDIN,则仍然会失败)。
也就是说,我想说:
echo "foo\nbar\nbaz" | randline
......而不是......
echo "foo\n\bar\nbaz" | randline -
如何做到这一点?
修改
感谢Doon!
#!/bin/bash
if [ "$( tty )" == 'not a tty' ]
then
STDIN_DATA_PRESENT=1
else
STDIN_DATA_PRESENT=0
fi
if [[ $# -ne 1 && $STDIN_DATA_PRESENT -eq 0 ]]
then
echo "Syntax: $0 [FILE (or \'-\' for STDIN)]"
echo $0 - display a random line from FILE
echo -e "\nWill also process piped STDIN if no arguments are given."
exit 1
fi
RAND=`cat /proc/sys/kernel/random/uuid | cut -c1-4 | od -d | head -1 | cut -d' ' -f2`
if [[ $1 && $1 != "-" ]]
then
LINES=`cat "$1" | wc -l`
LINE=`expr $RAND % $LINES + 1`
head -$LINE $1 | tail -1
else
piped=`cat -`
LINES=`echo "$piped" | wc -l`
LINE=`expr $RAND % $LINES + 1`
echo "$piped" | head -$LINE | tail -1
fi
答案 0 :(得分:2)
要从文件中获取随机行,您可以执行以下操作:
awk 'BEGIN{srand();}{printf "%04d %s\n", int(rand()*10000), $0}' < $FILENAME | sort | cut -f2- -d' ' | head -1
我们这样做:
答案 1 :(得分:1)
请参阅此处ksh: how to probe stdin?它适用于ksh,但提供了bash的答案