0

次のようなファイルがあります:

ああ

bbb

ccc

ddd

ええ


そして、このテキストファイルのランダムな行を取り、変数または何かとして返すことができるスクリプトをBASHで実行したいと考えています。

一部のAWKで実行できると聞きました。何か案は?

更新:私は今これを使用しています:

shuf -n 1 text.txt

助けてくれてありがとう!

4

3 に答える 3

2

次のようなスクリプトを使用して、singature-quotes ファイルからランダムな行を生成しました。

#!/bin/bash

QUOTES_FILE=$HOME/.quotes/quotes.txt
numLines=`wc -l $QUOTES_FILE | cut -d" " -f 1`

random=`date +%N`

selectedLineNumber=$(($random - $($random/$numLines) * $numLines + 1))
selectedLine=`head -n $selectedLineNumber $QUOTES_FILE | tail -n 1`

echo -e "$selectedLine"
于 2009-05-26T13:02:15.667 に答える
1

I would use sed with p argument...

sed -n '43p' 

where 43 could be a variable ...

i don't know much about awk but i guess you could do almost the same thing (however i don't know if awk is turing complete...)

于 2009-05-26T13:15:48.727 に答える
1

これは、外部ツールを使用しないbashの方法です

IFS=$'\n'
set -- $(<"myfile")
len=${#@}
rand=$((RANDOM%len+1))
linenum=0
while read -r myline
do
  (( linenum++ ))
  case "$linenum" in
   $rand) echo "$myline";;
  esac
done <"myfile"
于 2009-12-15T02:25:10.977 に答える